Deploying Next.js with Docker and Standalone Output
The default answer to "where should this deploy" is whichever platform removes the most work, and for many teams that is a managed host with git-based deploys. But the decision stops being free the moment you need a private network, a specific region, an on-premises database, or a bill that does not scale with request count. At that point you are building a container, and the differences between a Next.js app and a typical Node service start to matter: the build produces a client bundle, a server bundle, and static assets that all have to arrive in the right place at runtime.
This lesson covers both paths â what a managed platform does for you, and exactly what to put in the Dockerfile when you take that responsibility yourself.
Prerequisites
- !next.config options and environment variables
- !Basic Docker concepts: images, layers, ports
- !A Next.js project that builds cleanly with next build
What You'll Learn
- 1Pick a deployment target from stated requirements rather than habit
- 2Configure standalone output and understand what it emits
- 3Write a multi-stage image that runs as a non-root user
- 4Separate build-time and run-time environment configuration
Deployment targets and what each one costs
There is no universally correct choice, only a correct choice for a given set of constraints. The useful comparison is along the axes you will actually be asked about in a review: cold start behaviour, network position, operational surface, and how the bill moves as traffic grows.
| Target | Best for | You own | Typical failure mode |
|---|---|---|---|
| Managed platform (Vercel and similar) | Most web apps, rapid iteration | Very little | Cost at high, steady traffic |
| Container on a VM or orchestrator | Private networking, specific regions | Runtime, scaling, TLS | Cold starts and image size |
| Static export plus a separate API | Content sites with no server logic | Build pipeline only | Anything needing request-time rendering |
| Edge runtime only | Geographically distributed, lightweight logic | API compatibility limits | Runtime APIs not available |
The container path is worth taking when the application must reach a database that is not publicly reachable, when compliance requires the process to run inside your own account, or when a predictable per-hour cost beats a per-request one. It is worth avoiding when your team has no one who wants to own a Kubernetes cluster.
What standalone output actually produces
The standalone option changes the build so that the server only copies the modules it actually imports, instead of shipping your entire node_modules. That is the difference between an image measured in kilobytes of application code and one measured in hundreds of megabytes.
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
images: {
formats: ['image/avif', 'image/webp'],
// A custom loader or remotePatterns belongs here, not in the component.
remotePatterns: [{ protocol: 'https', hostname: 'cdn.example.com' }],
},
eslint: { ignoreDuringBuilds: false },
};
export default nextConfig;
After next build, three things matter in .next/standalone: a trimmed node_modules, a minimal server.js entry point, and the folder structure your code expects. Two directories are deliberately not copied â public and .next/static â because they are served as files rather than executed. Your Dockerfile has to bring them across by hand, and forgetting the static folder is the single most common cause of a container that starts successfully and serves unstyled pages.
A two-stage image that runs as nobody
Build in one stage where compilers and dev dependencies are legal, then copy the artifacts into a small final stage where they are not. The final process should never run as root: if an attacker reaches the Node process, a root container turns a code execution bug into a container escape risk.
# ---- build stage -------------------------------------------------
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Build args become PUBLIC_* vars available to the client bundle.
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
# ---- runtime stage -----------------------------------------------
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs \
&& adduser --system --uid 1001 nextjs
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1
CMD ["node", "server.js"]
Three details in that file prevent production surprises. HOSTNAME=0.0.0.0 is required inside a container because binding to localhost makes the process unreachable from outside it. The health check endpoint should be a real route that verifies the process can reach its dependencies, not a static 200, so a load balancer stops routing to an instance whose database connection has died. And the build argument for any NEXT_PUBLIC_ variable is a reminder that those values are inlined into the client bundle at build time â putting a secret there publishes it to every visitor.
Build-time versus run-time configuration
Next.js reads environment variables during the build for anything referenced by client code or by statically generated pages, and during the request for server-only code in a dynamic route. That split is why an image built once in CI often fails when started elsewhere: a database URL read during next build was baked into the HTML, or was simply missing and the build silently produced pages without data.
The practical rules are short. Anything prefixed NEXT_PUBLIC_ must be present at build time and must be safe to expose. Server-only secrets must be present at run time, and if a page is statically generated while reading them, the value is frozen into that page â so mark such routes dynamic or accept that they refresh only on the next build. Anything that should differ between staging and production but not require a rebuild belongs behind a server-only variable read inside a request or a Server Component.
Shipping without a visible gap
A container image makes releases atomic, which is exactly what makes a naive rollout painful: stop the old process, start the new one, and every request in that window fails. The two ingredients that remove the gap are a health check the orchestrator trusts and a graceful shutdown path in the application, working together.
// server.js â the standalone entry point, wrapped for clean shutdown
const { createServer } = require('http');
const next = require('next');
const app = next({ dev: false });
const handle = app.getRequestHandler();
async function main() {
await app.prepare();
const server = createServer((req, res) => handle(req, res));
server.listen(process.env.PORT || 3000, process.env.HOSTNAME, () => {
console.log(`ready on ${process.env.HOSTNAME}:${process.env.PORT}`);
});
const shutdown = (signal) => {
console.log(`${signal} received, draining connections`);
server.close(() => process.exit(0));
// Anything still open after the grace period is killed anyway.
setTimeout(() => process.exit(1), 15_000).unref();
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
}
main().catch((err) => {
console.error('failed to start', err);
process.exit(1);
});
The sequence a load balancer expects is: stop sending new traffic, let the health check fail, wait for in-flight requests to finish, then terminate. That is why server.close() alone is not enough â it stops accepting connections but does not bound how long a slow request can hold the process, so the timeout is what prevents an unresponsive pod from blocking a rollout forever. Pair it with a preStop hook or a termination grace period longer than the timeout, or the orchestrator will kill the process before your drain completes.
Verifying the deployment rather than trusting it
A container that starts is not a deployment that works. The checks worth running immediately after an image comes up are cheap and catch most configuration errors: hit the health endpoint and confirm a 200 with the expected body; load a statically generated page and confirm the HTML contains the data you expect rather than a skeleton; load a dynamic, authenticated page and confirm it renders per request; request an image through the optimizer and confirm the optimised variant returns rather than an error; and check that a server-only route cannot be reached from the browser bundle by searching the built client JavaScript for the secret's name.
That last check takes thirty seconds and has saved more incidents than any monitoring dashboard, because a leaked build-time variable is not a thing that ever goes red on its own.
Common Mistakes
Forgetting to copy .next/static and public into the runner stage
Fix: Copy both explicitly after the standalone folder, or the app serves HTML with no styles and missing assets.
Baking server secrets into NEXT_PUBLIC_ variables
Fix: Only non-sensitive values belong in that prefix; everything else is read from the environment at request time.
Running the Node process as root inside the container
Fix: Create a dedicated user in the runner stage and switch to it before CMD.
Using a health check that only proves the port is open
Fix: Point it at a route that checks a real dependency so unhealthy instances are removed from rotation.
Best Practices
- Pin base images by digest or at least by minor version for reproducible builds
- Keep the build stage free of secrets â nothing you would not paste into a public repo
- Expose only the server port and terminate TLS at the platform or ingress layer
- Log to stdout and let the orchestrator handle rotation
Key Takeaways
- Choose a target from requirements: private networking and cost predictability favour containers.
- output standalone trims node_modules, but public and .next/static must be copied in manually.
- Multi-stage builds keep compilers out of the final image; the final process should run as a non-root user.
- NEXT_PUBLIC_ values are compiled into the client bundle at build time; server secrets must exist at run time.
- Verify the running deployment: health, static pages, dynamic pages, image optimisation, and a client bundle scan.