Next.jsのdockerコンテナでホットリロードされないときの解決法


解決法

プロジェクトルートにnext.config.jsを作成する

next.config.js
module.exports = {
  webpackDevMiddleware: config => {
    config.watchOptions = {
      poll: 800,
      aggregateTimeout: 300,
    }
    return config
  },
}

実行環境

  • win10
  • docker-machine

ソースコード

.
├─ .next
├─ node_modules
├─ pages
│  └─ index.js
├─ docker-compose.yml
├─ Dockerfile
└─ package.json
docker-compose.yml
version: '3.3'

volumes:
  node_modules:

services:
  app:
    build: .
    container_name: next
    ports:
      - '80:3000'
    restart: always
    volumes:
      - '.:/app'
      - 'node_modules:/app/node_modules'
    tty: true
    stdin_open: true
# Dockerfile
FROM node:12

WORKDIR /app

COPY ./package*.json ./

CMD bash -c "npm install && npm run dev"
package.json
{
  "name": "nextjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.4.4",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
  }
}
pages/index.js
const Index = () => (
  <div>
    <p>Hello Next.js</p>
  </div>
)

export default Index