Next.js course ยท Module 9: Integrations and Advanced Features
Next.js and Docker - Containerizing Applications
In this lesson14
Just as ancient builders used standard molds to create identical building bricks, modern Docker lets us create standard, portable containers for our Next.js applications. In this lesson we will learn how to "package" our application into a Docker container that will run the same way in any environment - from a developer's local machine to production servers.
What is Docker and why is it useful for Next.js?
Docker is an application containerization platform that lets you package an application together with all its dependencies into lightweight, portable containers. For Next.js applications Docker offers many benefits:
Advantages of using Docker with Next.js
- Environment consistency - the application runs identically on every system
- Isolation - each application has its own dedicated environment
- Portability - easy migration between environments
- Scalability - simple horizontal scaling
- Versioning - ability to manage environment versions
Docker basics for Next.js
Docker file structure
Let's start by creating the basic Docker files in our Next.js project:
# Dockerfile
# Stage 1: Install dependencies
FROM node:18-alpine AS deps
WORKDIR /app
# Copy package files
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
# Install dependencies based on the lockfile
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
elif [ -f package-lock.json ]; then npm ci; \
elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
else echo "Lockfile not found." && exit 1; \
fi
# Stage 2: Build the application
FROM node:18-alpine AS builder
WORKDIR /app
# Copy dependencies from the previous stage
COPY /app/node_modules ./node_modules
# Copy the source code
COPY . .
# Build the Next.js application
RUN npm run build
# Stage 3: Production environment
FROM node:18-alpine AS runner
WORKDIR /app
# Add non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Copy public files
COPY /app/public ./public
# Copy the built application
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
CMD ["node", "server.js"]The .dockerignore file
Similar to .gitignore, the .dockerignore file specifies which files should be ignored when building a Docker image:
# .dockerignore
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.env
.git
.gitignore
.next
.nyc_output
coverage
.coverageNext.js configuration for Docker
Standalone Output
To optimize Docker image size, Next.js offers the standalone output option:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
experimental: {
// Optimizations for Docker
outputFileTracingRoot: path.join(__dirname, '../../'),
},
// Environment variables configuration
env: {
CUSTOM_KEY: process.env.CUSTOM_KEY,
},
// Image optimization
images: {
domains: ['example.com'],
unoptimized: process.env.NODE_ENV === 'development',
},
}
module.exports = nextConfigDocker Compose for development environments
Basic Docker Compose configuration
# docker-compose.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
target: development
ports:
- "3000:3000"
environment:
- NODE_ENV=development
volumes:
- .:/app
- /app/node_modules
- /app/.next
command: npm run dev
database:
image: postgres:15
environment:
POSTGRES_DB: nextjs_app
POSTGRES_USER: user
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:Dockerfile for the development environment
# Dockerfile.dev
FROM node:18-alpine
WORKDIR /app
# Install global dependencies
RUN npm install -g nodemon
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy source code
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]Multi-stage Dockerfile for production
Optimized Dockerfile
# Dockerfile.prod
# Build stage
FROM node:18-alpine AS build
WORKDIR /app
# Install dependencies
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force
# Copy and build the application
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine AS production
WORKDIR /app
# Create user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# Copy only the necessary files
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
COPY /app/public ./public
USER nextjs
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
HEALTHCHECK \
CMD curl -f http://localhost:3000/api/health || exit 1
CMD ["node", "server.js"]Managing environment variables
Environment file
# .env.docker
NODE_ENV=production
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_URL=postgresql://user:password@database:5432/nextjs_app
REDIS_URL=redis://redis:6379
JWT_SECRET=your-secret-keyDocker Compose with environment files
# docker-compose.prod.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.prod
ports:
- "3000:3000"
env_file:
- .env.docker
depends_on:
- database
- redis
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- app
restart: unless-stopped
database:
image: postgres:15
env_file:
- .env.docker
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
redis:
image: redis:7-alpine
restart: unless-stopped
volumes:
postgres_data:Image optimization Docker
Reducing image size
# Dockerfile.optimized
FROM node:18-alpine AS base
# Install only the required packages
RUN apk add --no-cache libc6-compat
FROM base AS deps
WORKDIR /app
# Copy dependency files
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
# Install dependencies
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
elif [ -f package-lock.json ]; then npm ci; \
elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i; \
else echo "Lockfile not found." && exit 1; \
fi
FROM base AS builder
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
# Build with optimizations
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY /app/public ./public
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]Security in Docker containers
Security best practices
# Dockerfile.secure
FROM node:18-alpine AS base
# Update system packages
RUN apk update && apk upgrade
# Install security tools
RUN apk add --no-cache dumb-init
# Use a non-admin user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
FROM base AS deps
WORKDIR /app
# Copy only the necessary files
COPY package*.json ./
# Install with a security audit
RUN npm ci --only=production && npm audit fix
FROM base AS builder
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
# Security scan before building
RUN npm audit
# Build the application
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
# Copy with appropriate permissions
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
# Set the user
USER nextjs
# Healthcheck for monitoring
HEALTHCHECK \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1
EXPOSE 3000
# Use dumb-init for better process management
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "server.js"]Monitoring and logging
Logging configuration
// utils/logger.js
import winston from 'winston'
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: { service: 'nextjs-app' },
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
})
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}))
}
export default loggerHealth Check endpoint
// pages/api/health.js
export default function handler(req, res) {
const healthcheck = {
uptime: process.uptime(),
message: 'OK',
timestamp: Date.now(),
environment: process.env.NODE_ENV,
version: process.env.npm_package_version,
}
try {
// Check connections to database, Redis, etc.
res.status(200).json(healthcheck)
} catch (error) {
healthcheck.message = error.message
res.status(503).json(healthcheck)
}
}CI/CD with Docker
GitHub Actions with Docker
# .github/workflows/docker.yml
name: Docker Build and Deploy
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: \
myapp/nextjs:latest
myapp/nextjs:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to production
run: |
echo "Deploying to production server"
# Deployment code for production server goes hereScaling and orchestration
Kubernetes Deployment
# k8s/deployment.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nextjs-app
spec:
replicas: 3
selector:
matchLabels:
app: nextjs-app
template:
metadata:
labels:
app: nextjs-app
spec:
containers:
- name: nextjs-app
image: myapp/nextjs:latest
ports:
- containerPort: 3000
env:
- name: NODE_ENV
value: "production"
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: nextjs-service
spec:
selector:
app: nextjs-app
ports:
- port: 80
targetPort: 3000
type: LoadBalancerBest practices
1. Layer optimization
# Good - group commands together
RUN apk update && \
apk add --no-cache git curl && \
rm -rf /var/cache/apk/*
# Bad - separate layers
RUN apk update
RUN apk add --no-cache git
RUN apk add --no-cache curl2. Using .dockerignore
# .dockerignore
node_modules
.git
.gitignore
README.md
Dockerfile
.dockerignore
npm-debug.log
coverage
.nyc_output3. Managing secrets
# Use Docker secrets instead of environment variables
docker service create \
--name nextjs-app \
--secret db_password \
--secret api_key \
myapp/nextjs:latest4. Monitoring and alerting
// middleware/monitoring.js
import prometheus from 'prom-client'
const httpDuration = new prometheus.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status'],
buckets: [0.1, 0.5, 1, 2, 5]
})
export function monitoringMiddleware(req, res, next) {
const start = Date.now()
res.on('finish', () => {
const duration = (Date.now() - start) / 1000
httpDuration
.labels(req.method, req.route?.path || req.path, res.statusCode)
.observe(duration)
})
next()
}Troubleshooting
Common problems and solutions
Problem with npm ci on Alpine Linux
# Solution: install python and make RUN apk add --no-cache python3 make g++Issues with Next.js Image Optimization
// next.config.js module.exports = { images: { unoptimized: true, // For environments without sharp }, }Memory issues
# Limit Node.js memory ENV NODE_OPTIONS="--max-old-space-size=1024"
Summary
Docker combined with Next.js is a powerful pairing that enables:
- Consistent environments across every stage of development
- Easy scaling of applications in the cloud
- Safe deployments with process isolation
- Efficient management of dependencies and versions
Just as ancient builders created durable structures using standardized components, Docker lets us build reliable, scalable Next.js applications that behave the same in every environment.
In the following lessons we will explore advanced container orchestration techniques and strategies for deploying Next.js applications in cloud environments.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is NOT a direct benefit of containerizing Next.js with Docker?
2. Which practice is INCORRECT for production deployment of Next.js in Docker?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps of containerizing a Next.js application with Docker
- Click in order
Arrange the steps of Docker orchestration in order.
- Vertical ordering
Arrange the correct order of basic directives in a Dockerfile for a Next.js application:
- Code editor
Write a multi-stage Dockerfile for Next.js: install the dependencies and build the app in a stage based on a node image, copy only the build output into the final stage (COPY --from) and start the app with CMD.