Next.jsDockerNginxInfrastructure

Deploying Next.js to Production with Docker Standalone and Nginx Reverse Proxy

แนวทางการ Deploy Next.js ขึ้น Production ด้วย Docker และ Nginx Reverse Proxy

Author: Patipan Plonying···6 min read

Why Use Standalone Mode When Running Next.js in Docker?

When deploying a Next.js application to a self-managed Linux VPS or container cluster, a common pitfall is ending up with bloated Docker images (often exceeding 1 GB) by copying the entire node_modules directory into the runtime container.

Patipan Plonying recommends enabling `output: 'standalone'` in `next.config.ts`. Next.js automatically traces only the production files required to run the server and outputs a minimal `.next/standalone` bundle—shrinking container image sizes down to a few hundred megabytes and significantly improving cold-start times.

next.config.tstypescript
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  poweredByHeader: false,
};

export default nextConfig;

Production Multi-Stage Dockerfile

Splitting the Dockerfile into three distinct stages—`deps` (installing packages), `builder` (compiling the application), and `runner` (the lean production image)—maximizes Docker layer caching and hardens security by executing the Node.js server under a non-root system user.

Dockerfiledockerfile
FROM node:20-alpine AS base

FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

RUN addgroup --system --gid 1001 nodejs && \
    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
CMD ["node", "server.js"]

Configuring Nginx as a Reverse Proxy & Enforcing Canonical Domains

With the Next.js container listening internally on port 3000, Nginx sits on ports 80/443 to handle SSL/TLS termination, enforce a permanent 301 redirect from the bare domain to `www`, and proxy HTTP/1.1 and WebSocket upgrade headers cleanly to the container.

/etc/nginx/conf.d/pl-patipan.confnginx
server {
    listen 80;
    server_name pl-patipan.in.th;
    return 301 https://www.pl-patipan.in.th$request_uri;
}

server {
    listen 443 ssl http2;
    server_name www.pl-patipan.in.th;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}