No. 34DevOps8 min read2,192 words
Docker for web apps: a lean Next.js setup, no overkill
How to dockerize a Next.js or Node app: one multi-stage Dockerfile, a compose file for local dev with Postgres, and the traps that bloat images or leak secrets.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01Many web apps do not need Docker: if you deploy one runtime to a managed platform, the platform builds and runs it for you. Docker pays off when several services must agree on versions or you self-host.
- 02Use a multi-stage Dockerfile so the final image carries only build output, and set output: 'standalone' in Next.js so the server ships just the files it actually needs.
- 03Start from node:24-slim rather than alpine. Alpine uses musl instead of glibc, which can break native modules like sharp or bcrypt.
- 04Write a .dockerignore before your first build, and never bake secrets or .env files into image layers. Pass them at runtime or as BuildKit build secrets.
- 05NEXT_PUBLIC_ variables are inlined at build time, so one image promoted across environments will carry the values from the environment where it was built.
On this page ยท 09
You need Docker for a web app when several moving parts must agree on versions, when you self-host, or when you want one identical artifact for your laptop, CI and production. You do not need it if you deploy a single Next.js or Node app to a managed platform that builds it for you. When you do need it, the right amount is small: one multi-stage Dockerfile, one compose file for local development, and a handful of habits that keep images lean and secrets out of them.
Most Docker tutorials for web apps are either three lines that fall over in production or a forty-file Kubernetes saga you will never need. This guide is the boring middle, and it is the setup we reach for in our cloud and DevOps work whenever a project genuinely calls for containers.
Do you actually need Docker for your web app?
Honest answer first: a lot of web apps ship fine without it. If you deploy a Next.js app to Vercel or a Node API to a platform like Render, the platform builds and runs it for you, and adding a Dockerfile gives you one more thing to maintain.
| Situation | Docker worth it? | Why |
|---|---|---|
| One Next.js app on a managed platform, managed database | Usually no | The platform already builds and runs it |
| Several services (API, worker, Postgres, Redis) and a team on different laptops | Yes | Everyone runs identical versions with one command |
| Self-hosting on your own servers or a container platform | Yes | The image is your deployable unit |
| CI needs the same environment as production | Often | One image tested and shipped, no drift |
| Native dependencies that are painful to install locally | Often | The image pins the system libraries once |
If your app is "one runtime, one managed database, deploy to a platform", you can skip this and come back when it hurts. For everything else, the goal is a single image that runs the same on your laptop, in CI and on the server.
A multi-stage Dockerfile for Next.js that stays small
The single biggest mistake is shipping your whole build toolchain in the final image. Production does not need dev dependencies, the TypeScript compiler or your source files. Multi-stage builds fix this: you build in one stage and copy only the output into a clean final stage.
Here is a Dockerfile for a Next.js 16 app using standalone output. The same shape works for a plain Node API with small changes.
# syntax=docker/dockerfile:1
# 1. Install dependencies. Re-runs only when the lockfile changes.
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
# 2. Build the app.
FROM node:24-slim AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
# NEXT_PUBLIC_ values are inlined here, at build time.
ARG NEXT_PUBLIC_APP_URL
ENV NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL
RUN npm run build
# 3. Runtime image: no build tools, no source, no dev dependencies.
FROM node:24-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
# The standalone server must listen on all interfaces inside a container.
ENV HOSTNAME=0.0.0.0
RUN groupadd --system --gid 1001 nodejs \
&& useradd --system --uid 1001 --gid nodejs 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
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
CMD node -e "fetch('http://127.0.0.1:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.js"]For this to work, turn on standalone output:
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;The Next.js output docs explain what this does: during the build, Next.js traces exactly which files the server needs and copies them, including only the required parts of node_modules, into .next/standalone with a minimal server.js. It does not copy public or .next/static, which is why the Dockerfile copies those two folders explicitly.
Why each stage exists
depsisolates the dependency install so it only re-runs whenpackage-lock.jsonchanges, not every time you edit a component. The cache mount keeps npm's download cache between builds on the same machine.buildercompiles the app. It is large and full of tooling, and that is fine, because nothing from it ships except the output.runnerstarts from a clean base and receives only the artifacts. It runs as a non-root user, listens on0.0.0.0, and exposes a health check.
Two lines people often miss. HOSTNAME=0.0.0.0 matters because a server listening only on localhost inside a container is unreachable from outside it. And the health check uses Node's built-in fetch because slim images do not include curl. Point it at a cheap route such as /api/health that returns 200 without touching the database, so a slow database does not get healthy containers killed.
Why slim and not alpine
You will see node:24-alpine everywhere because it is smaller. It is also built on musl libc instead of glibc, which occasionally breaks native modules (sharp, bcrypt, some database drivers) in ways that cost you an afternoon. The official Node image docs note that musl differences can cause problems depending on your libc requirements. node:24-slim is Debian-based, a bit larger, and far less likely to surprise you. Start with slim. Switch later only if size genuinely matters and your dependencies are proven on alpine.
Pin the base image to a Node major (node:24-slim), never node:latest, which moves under you and breaks reproducibility. Node 24 is an LTS line, which is what you want under a production server.
A .dockerignore is not optional
The build context is everything Docker sends to the builder. Without a .dockerignore, COPY . . drags in your local node_modules, your .next cache, your .git history and your .env files. Builds slow down, cache busts constantly, and secrets can end up inside image layers.
node_modules
.next
.git
.env
.env.*
npm-debug.log*
Dockerfile
compose.yaml
.dockerignore
README.md
coverageWrite this before your first build, not after you notice the image is over a gigabyte.
What makes Docker images bloated and slow to build
When we take over a project with a slow or huge image, the cause is almost always on this list.
| Symptom | Usual cause | Fix |
|---|---|---|
| Image is huge | Whole node_modules (with dev deps) copied into the final stage | Multi-stage build plus standalone output |
| Every build reinstalls everything | Source copied before npm ci | Copy the lockfile and install first, then copy source |
| Build context takes ages to send | No .dockerignore | Exclude node_modules, .next, .git |
| Native module crashes at runtime | Alpine and musl libc | Use node:24-slim |
Secrets visible in docker history | COPY .env or ARG used for a secret | Runtime env vars or BuildKit secret mounts |
| Container unreachable | Server bound to localhost | Set HOSTNAME=0.0.0.0 |
Layer ordering deserves one more sentence. Docker caches layers top to bottom and invalidates everything after the first change. Order your Dockerfile from least to most frequently changed, so a tweak to one component never reinstalls every dependency.
Docker Compose for local development
The Dockerfile above is for production. Local development wants something different: hot reloading, your real database, and no rebuild every time you save. That is what compose.yaml is for.
services:
app:
build:
context: .
target: deps
command: npm run dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
DATABASE_URL: postgres://app:app@db:5432/app
depends_on:
db:
condition: service_healthy
db:
image: postgres:18
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app
ports:
- "5432:5432"
volumes:
# Postgres 18+ images use /var/lib/postgresql as the volume root.
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d app"]
interval: 5s
timeout: 5s
retries: 5
volumes:
pgdata:Three details matter here.
target: deps reuses the dependency stage from your production Dockerfile, so development and production install from the same lockfile.
The pair of volumes (.:/app plus the anonymous /app/node_modules) mounts your source for live editing while keeping the container's own node_modules. Without that second volume, your host's node_modules would shadow the container's, and anything compiled for the container's architecture breaks.
The health check plus condition: service_healthy makes the app wait until Postgres actually accepts connections, not just until the container starts. Docker documents this in its guide to controlling startup order, and it kills the classic "connection refused on first boot" race.
One version note that trips people up: the official Postgres image changed its data layout in version 18, and the volume now mounts at /var/lib/postgresql instead of /var/lib/postgresql/data. If you upgrade an older compose file without changing the mount, your data will not be where you think it is. Major version upgrades also need a dump and restore (or pg_upgrade), not just a new tag.
Run docker compose up and you have your app and a real Postgres talking to each other, with data that survives restarts in the pgdata volume. If bind mounts are slow on your machine, Compose Watch can sync source changes into the container instead.
Migrations and seed data
Keep schema changes out of the Dockerfile. Run them as an explicit step, either a one-off command or your migration tool.
-- migrations/001_init.sql
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);Let your migration tool (Drizzle, Prisma, node-pg-migrate) apply it with something like docker compose run --rm app npm run db:migrate. The database image stays generic and your schema stays in version control. In production, run migrations as a separate step before new containers take traffic, which our guide to CI/CD small teams can maintain covers along with the expand-and-contract pattern for zero-downtime schema changes.
Secrets and environment variables in Docker
This is where Docker setups quietly become security problems, so it gets its own section.
Never bake secrets into the image. Anything you COPY or set with ENV in a stage that ends up in the final image lives in a layer forever and travels with the image to every registry and server it touches. Pass runtime secrets as environment variables from your platform's secret store.
Use build secrets for build-time credentials. If the build needs a token, for example to install a private npm package, mount it with a BuildKit secret so it is available to one RUN step and never written into a layer. ARG is not a safe substitute: build arguments show up in the image history.
Know which variables are frozen at build time. Next.js inlines NEXT_PUBLIC_ variables into the browser bundle during next build. If you build one image and promote it from staging to production, those values stay whatever they were at build time. Server-only variables are read at runtime and can differ per environment. Either build per environment, or keep public configuration server-side and pass it to the client yourself.
Run as a non-root user (the Dockerfile above does), keep the base image patched by rebuilding regularly, and scan images in CI if you handle sensitive data. Our web application security checklist covers the rest of the surface.
Running the image in production
A container image is only half a deployment. Before you call it done:
- Build once in CI and tag the image with the commit SHA, so what you deploy is exactly what you tested.
- Run it on a managed container platform unless you have a real reason to operate servers. You keep the portability of Docker without patching hosts. Our roundup of the best hosting for Next.js compares the managed options, container platforms included.
- Point the health check at a cheap route and let the platform restart unhealthy containers.
- Log to stdout in structured JSON so the platform collects it. Our observability basics post shows the setup.
- Keep containers stateless. No sessions in memory, no uploads on local disk. That is what lets you run more copies when traffic jumps, as we explain in scaling a web app when traffic spikes.
The Node.js Docker team's best practices guide is worth ten minutes, particularly the notes on signal handling and running as the node user.
The setup that covers most projects
You do not need a platform team to run Docker well for a web app. One multi-stage Dockerfile that ships only build output, a .dockerignore so your context stays clean, a compose file with a health-checked database, and strict rules about secrets cover the vast majority of real projects. Start there, keep it small, and add complexity only when a specific problem forces your hand.
If your Dockerfile has quietly grown to a gigabyte, or you are moving off a platform and want a container setup your team can own, tell us about it. It is exactly the kind of cleanup our cloud and DevOps team enjoys.
FAQ ยท 05 questions
Frequently asked questions
Do I need Docker to deploy a Next.js app?
No. Platforms like Vercel, Netlify and many Node hosts build and run a Next.js app directly from your repository. Docker becomes useful when you self-host, run several services that must share exact versions, or want one identical artifact for local development, CI and production.
Should I use node alpine or node slim as my base image?
Start with the Debian-based slim image. Alpine is smaller but uses musl libc instead of glibc, and native modules such as sharp, bcrypt or some database drivers can fail or behave differently on it. Move to alpine only if image size genuinely matters and your dependencies are proven to work there.
How big should a Next.js Docker image be?
With standalone output and a multi-stage build, the final image is mostly the Node base image plus your traced server files and static assets. If your image is many times larger than the base image, the usual causes are copying the whole node_modules folder, shipping dev dependencies, or a missing .dockerignore.
Is Docker Compose good enough for production?
For a single server running a handful of containers, Compose can work, but you take on backups, TLS, updates, monitoring and restarts yourself. Most small teams are better served using Compose for local development and running the production image on a managed container platform with a managed database.
How do I pass environment variables to a Dockerized Next.js app?
Pass server-side variables at runtime with the container's environment settings, so one image can run in any environment. Variables prefixed with NEXT_PUBLIC_ are different: Next.js inlines them into the browser bundle during the build, so they must be set when the image is built.