LoginSignup
3
1

公式Dockerfileとcreate-next-appでNext.jsプロジェクトを開始

Posted at

はじめに

Next.jsは公式でDockerfileを提供しており、非常に始めやすいです。

しかし公式のHow to useに則ってプロジェクトのスケルトンを作成するのは少し自由度が低いですよね。純粋にcreate-next-appしたいものです。

この記事では公式のDockerfileを活用しつつ、自身でcreate-next-appすることでプロジェクトの初期設定を行う方法を紹介します。

手順

1. 新しいディレクトリの作成

まずはプロジェクト用のディレクトリを作成し、移動します。

$ mkdir nextjs-docker
$ cd nextjs-docker

2. Dockerを利用してcreate-next-app実行

公式のDockerfileのベースイメージがnode:18-alpineですので、これをpullしてcreate-next-appを実行します。

$ docker run --rm -it -v $(pwd):/app node:18-alpine sh -c "cd /app && npx create-next-app ."

Need to install the following packages:
  create-next-app@13.4.19
Ok to proceed? (y) y
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias? … No / Yes
Creating a new Next.js app in /app.

Using npm.

Initializing project with template: app-tw 

これで Next.jsプロジェクトを作成できました。

3. 公式のDockerfileを取得

$ curl https://raw.githubusercontent.com/vercel/next.js/canary/examples/with-docker/Dockerfile > Dockerfile

4. standaloneで起動設定の追加

公式Dockerfileはstandaloneでのビルドを想定しているため、その設定を行います。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
    output: 'standalone'
}

module.exports = nextConfig

5. Dockerイメージのビルドと起動

$ docker build -t next .
$ docker run -p 3000:3000 next

これで、http://localhost:3000 にアクセスすると、Next.jsの初期画面が表示されます🚀。

まとめ

今更ですがよく使うので備忘録です。
皆様のNext.jsがより快適になることを祈っています🫶。

Tips:compose.yamlは雑に作っています。

commpose.yaml
version: '3.7'
services:
  next:
    image: node:18-alpine
    ports:
      - "3000:3000"
    volumes:
      - ./:/app
    working_dir: /app
    command: sh -c "npm i && npm run dev"
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1