Docker
DevOps
Deployment
Docker pour Next.js : Guide de déploiement complet
Dockerisez votre application Next.js avec Dockerfile optimisé, docker-compose pour le développement, et déploiement production.
Emmanuel Mulonda28 juin 202611 min de lecture
Introduction
Docker permet de garantir que votre application fonctionne identiquement en développement et en production. Voici comment dockeriser un projet Next.js.
Dockerfile Optimisé
# Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production
# Stage 2: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Stage 3: Production
FROM node:20-alpine 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 --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
CMD ["node", "server.js"]
Configuration Next.js
// next.config.ts
const nextConfig = {
output: "standalone",
// ... autres options
};
Docker Compose (Développement)
# docker-compose.yml
services:
app:
build: .
ports:
- "3000:3000"
volumes:
- ./src:/app/src
- ./public:/app/public
environment:
- DATABASE_URL=postgresql://postgres:password@db:5432/wabtechs
- NEXTAUTH_SECRET=dev-secret
- NEXTAUTH_URL=http://localhost:3000
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-alpine
ports:
- "5432:5432"
environment:
POSTGRES_DB: wabtechs
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:
Build & Run
# Développement
docker compose up
# Production
docker compose -f docker-compose.prod.yml up -d
# Build image
docker build -t wabtechs-platform .
# Run
docker run -p 3000:3000 wabtechs-platform
Docker Compose Production
# docker-compose.prod.yml
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
- NEXTAUTH_URL=${NEXTAUTH_URL}
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000"]
interval: 30s
timeout: 10s
retries: 3
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- app
Docker
DevOps
Deployment