Back to blog

Monday, December 30, 2024

Dockerizing Next.js Applications: A Complete Implementation Guide

cover

Guide: Dockerizing a Next.js Application

This guide will help you containerize your Next.js application using Docker.

Project Structure

your-nextjs-app/
├── Dockerfile
├── compose.yaml
├── .dockerignore
└── ... (other Next.js files)

1. Dockerfile Using npm

FROM node

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy all files
COPY . .

# Expose port 3000
EXPOSE 3000

# Start development server
CMD npm run dev

This Dockerfile:

  • Uses Node.js as base image
  • Sets /app as working directory
  • Copies package files first for better caching
  • Installs dependencies
  • Copies remaining project files
  • Exposes port 3000
  • Runs the development server

Dockerfile using pnpm

FROM node

# Install pnpm
RUN npm install -g pnpm

WORKDIR /app

# Copy package files
COPY package*.json ./
COPY pnpm-lock.yaml ./

# Install dependencies using pnpm
RUN pnpm install

COPY . .

EXPOSE 3000

# Use pnpm for running commands
CMD pnpm dev

2. Docker Compose (compose.yaml)

version: "3.8"
services:
  frontend:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    develop:
      watch:
        - path: ./package.json
          action: rebuild
        - path: ./next.config.js
          action: rebuild
        - path: ./package-lock.json
          action: rebuild
        - path: .
          target: /app
          action: sync
    environment:
      - DB_URL=mongodb+srv://your-mongodb-url
volumes:
  tasked:

This compose file:

  • Specifies Docker Compose version
  • Defines frontend service
  • Maps port 3000
  • Sets up file watching for development:
    • Rebuilds when package files or Next.js config changes
    • Syncs project files to container
  • Configures environment variables
  • Defines a volume for persistence

3. .dockerignore

node_modules
.next
.git
README.md
.env.local

This prevents unnecessary files from being copied into the container.

Usage

  1. Build and start containers:
docker compose up --watch
  1. Stop containers:
docker compose down

Key Features

  • Hot reload support
  • Development environment setup
  • Environment variable management
  • Volume management for persistence
  • File watching for automatic rebuilds

Development Workflow

  1. Make changes to your Next.js code
  2. Docker will automatically detect changes
  3. Container will rebuild or sync as needed
  4. View changes at localhost:3000

This setup provides a development-friendly environment while maintaining the benefits of containerization. The watch feature ensures quick feedback during development, while the compose file manages all the necessary services and configurations.

Would you like me to explain any specific part in more detail?