A Next.js app that runs perfectly with npm run dev often falls apart in its first container: the page won't load, a native module refuses to start, or the image dies on the server with exec format error. These aren't Docker bugs, just differences between your laptop and a Linux container that the app quietly depended on. Below is each one with a fix, then a production Dockerfile and a checklist.
TL;DR
- Inside a container,
localhostmeans the container itself. Bind to0.0.0.0, setHOSTNAME=0.0.0.0for the standalone server, and publish the port with-p. - Never copy your machine's
node_modulesinto the image: add a.dockerignoreand runnpm ciinside it so native binaries (sharp, bcrypt, esbuild, SWC) are built for Linux. - Images built on Apple Silicon are
arm64by default. Use--platform linux/amd64ordocker buildxwhen the server is amd64. - In Compose dev setups, protect the image's
node_moduleswith an anonymous volume and turn on polling if hot reload misses changes. NEXT_PUBLIC_variables are inlined at build time, so pass them as build args. Shell scripts need LF line endings, enforced with.gitattributes.
The browser cannot reach the app
The container starts, the logs say the server is ready, and http://localhost:3000 still gives "connection refused" or "this site can't be reached".
A container has its own network namespace and loopback interface. Published ports are forwarded to its network interface (usually eth0), not its loopback. A server bound to 127.0.0.1 or localhost only accepts loopback connections, so forwarded traffic is refused. 0.0.0.0 means every interface.
You can see the effect without Docker. This script binds to HOST, then connects over loopback and over another local IPv4 address standing in for eth0:
import http from "node:http";
import net from "node:net";
import os from "node:os";
const host = process.env.HOST ?? "0.0.0.0";
const port = 3456;
// The first non-loopback IPv4 address plays the role of the container's eth0.
const external = Object.values(os.networkInterfaces())
.flat()
.find((iface) => iface.family === "IPv4" && !iface.internal);
if (!external) {
console.log("No non-loopback IPv4 interface found; connect to a network and retry.");
process.exit(1);
}
function probe(label, address) {
return new Promise((resolve) => {
const socket = net.connect({ host: address, port });
socket.once("connect", () => {
console.log(`${label.padEnd(14)} connected`);
socket.destroy();
resolve();
});
socket.once("error", (err) => {
console.log(`${label.padEnd(14)} ${err.code}`);
resolve();
});
});
}
const server = http.createServer((req, res) => res.end("ok\n"));
server.listen(port, host, async () => {
console.log(`server bound to ${host}`);
await probe("loopback", "127.0.0.1");
await probe("other address", external.address);
server.close();
});Save it as bind-demo.mjs and run it twice:
HOST=127.0.0.1 node bind-demo.mjs
HOST=0.0.0.0 node bind-demo.mjsserver bound to 127.0.0.1
loopback connected
other address ECONNREFUSED
server bound to 0.0.0.0
loopback connected
other address connectedCustom Node servers
With Express, Fastify or plain http, look for a hard-coded host: app.listen(3000, "localhost") works on your laptop and nowhere else. Read host and port from the environment:
import http from "node:http";
const host = process.env.HOST ?? "0.0.0.0";
const port = Number(process.env.PORT ?? 3000);
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("ok\n");
});
server.listen(port, host, () => {
const { address, port: actualPort } = server.address();
console.log(`listening on ${address}:${actualPort}`);
});Next.js start and the standalone server
In Next.js 14, next start and next dev listen on 0.0.0.0 by default, and next start reads PORT from the environment. Problems usually come from a script pinning the host:
"scripts": {
"dev": "next dev",
"build": "next build",
- "start": "next start -H localhost"
+ "start": "next start -H 0.0.0.0"
}The standalone server (node server.js, covered below) takes no CLI flags; it reads PORT and HOSTNAME from the environment. In Next.js 14 the defaults are 3000 and 0.0.0.0; some earlier releases used localhost, so check the generated .next/standalone/server.js.
The catch: Docker sets HOSTNAME in every container to the container's hostname (the short container ID by default), and Kubernetes sets it to the pod name. The standalone server then binds to the container's own address, not every interface. Published ports usually keep working, but anything connecting to localhost inside the container, such as a HEALTHCHECK or kubectl port-forward, is refused. Set it explicitly:
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
CMD ["node", "server.js"]Publish the port
EXPOSE 3000 is documentation, not publishing. Use -p host:container (or ports: in Compose), with the container side matching the app's port:
# Host port 3000 -> container port 3000
docker run --rm -p 3000:3000 my-next-app
# The app listens on 8080 inside the container, still reachable on localhost:3000
docker run --rm -p 3000:8080 -e PORT=8080 my-next-appStill stuck? Test inside the container. If this works and the browser doesn't, the bind address or port mapping is wrong:
docker exec -it my-container node -e "fetch('http://127.0.0.1:3000/').then((r) => console.log(r.status))"Never copy node_modules into the image
Some packages contain compiled native code: sharp (used by next/image), bcrypt, esbuild, and the SWC compiler inside Next.js. npm installs binaries for the OS, CPU and C library of the machine running the install. Run npm install on Windows or macOS, COPY . . into a Linux image, and those binaries fail to load. Typical symptoms (wording varies by version):
- sharp says it could not load the
"sharp"module using thelinux-x64runtime. bcryptand other node-gyp addons fail withinvalid ELF header: Linux rejecting a Windows or macOS binary.- esbuild says you installed it for another platform.
- Next.js reports
Failed to load SWC binary for linux/x64.
Here is the Dockerfile that causes it:
FROM node:20-bookworm-slim
WORKDIR /app
COPY . .
RUN npm run build
CMD ["npm", "start"]COPY . . sends your local node_modules and .next into the image. The fix has two parts. First, a .dockerignore at the root of the build context (usually the project root, next to the Dockerfile) that keeps those folders out:
node_modules
.next
.git
npm-debug.log*
.env*.localSecond, install dependencies inside the image from the lockfile:
FROM node:20-bookworm-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]npm ci installs exactly what package-lock.json says and fails if it disagrees with package.json. Copying the package files first also lets Docker reuse the cached npm ci layer when only code changes.
Note: The C library matters too. Alpine uses musl, Debian-based images use glibc, and native binaries target one or the other, so keep the install and runtime stages on the same base image family. If the build or app later complains that a platform-specific package such as
@next/swc-linux-x64-gnuis missing, the lockfile may lack that platform's optional dependencies; regenerating it with a recent npm usually helps.
Apple Silicon images on amd64 servers
On an M-series Mac, docker build produces a linux/arm64 image. Pull it on a typical amd64 VPS or CI runner and the container dies with output like this (wording varies by Docker version):
WARNING: The requested image's platform (linux/arm64/v8) does not match the detected host platform (linux/amd64) and no specific platform was requested
exec /usr/local/bin/docker-entrypoint.sh: exec format errorexec format error means the kernel was asked to run a binary for a different CPU. Check what you built, then build for the server's architecture:
# Prints something like linux/arm64 or linux/amd64
docker image inspect my-next-app --format '{{.Os}}/{{.Architecture}}'
# Build for an amd64 server from any machine
docker build --platform linux/amd64 -t my-next-app .
# Or build one multi-architecture image and push it
docker buildx build --platform linux/amd64,linux/arm64 -t registry.example.com/my-next-app:1.0.0 --push .Cross-building runs under emulation, so it is slower, especially for packages compiled from source. Multi-platform builds may also need a builder created with docker buildx create --use. Docker Desktop ships emulation; on a plain Linux host or CI runner you may need to register QEMU first (for example with the tonistiigi/binfmt image or your CI's setup-qemu step), or RUN steps fail with that same exec format error. In Compose, add platform: linux/amd64 to the service.
Running npm ci inside the image pays off here too: an amd64 build fetches amd64 binaries. Avoid hard-coding FROM --platform=linux/amd64, or every local run on your Mac is emulated too; pass the platform at build time or build in CI on amd64 runners.
Docker Compose for local development
For development you usually bind-mount the source so edits show up without rebuilding. That brings two problems.
The bind mount hides node_modules
services:
web:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/appWith a Dockerfile.dev like this:
FROM node:20-bookworm-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev", "--", "--hostname", "0.0.0.0"]The image has a correct, Linux-built node_modules, but the bind mount replaces /app with your project folder at runtime. With no node_modules on the host, npm run dev fails with a next: not found style error; with one, the container loads your Windows or macOS binaries and you're back to the native module errors. Avoid npx next dev here: without a TTY, npx assumes --yes and quietly downloads an unpinned next instead of failing.
The fix is an anonymous volume for the folders the container should own:
services:
web:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
- /app/.next
environment:
WATCHPACK_POLLING: "true"The more specific mount wins, so /app/node_modules comes from a volume, not the host. When Docker creates an empty volume over a path with content in the image, it copies that content in first, so the container sees the image's node_modules; .next works the same way. You can still run npm install on the host for your editor; the container won't see it.
One gotcha: Compose reuses anonymous volumes when recreating a container, so after a dependency change the old node_modules can return. Start fresh with:
docker compose up --build --renew-anon-volumesHot reload does not see your changes
File watchers rely on filesystem change events. When a Windows folder (or, depending on the file sharing mode, a macOS one) is bind-mounted into Docker Desktop's Linux VM, those events often never reach the container, so saving a file does nothing.
Polling works everywhere at some CPU cost. Next.js's webpack dev server uses watchpack, which reads WATCHPACK_POLLING (the environment entry above); in the copy bundled with Next.js 14, true enables polling and a number sets the interval in milliseconds. Turbopack has its own watcher, so check the docs for your version. On Windows, keeping the project in the WSL 2 filesystem usually avoids the problem.
NEXT_PUBLIC_ variables are frozen at build time
This breaks the "build once, configure per environment" habit. Code like this runs in the browser:
"use client";
export function ApiStatus() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
return <p>API: {apiUrl ?? "not set"}</p>;
}The browser has no real environment to read from. During next build, Next.js replaces process.env.NEXT_PUBLIC_API_URL with the literal value from the build environment (in Next.js 14, in the server bundles too, when the variable is set). So passing -e NEXT_PUBLIC_API_URL to docker run doesn't fix the browser: if the variable was missing during the build, client code gets undefined. Worse, server-rendered HTML on dynamic routes can see the runtime value while the browser can't, which surfaces as a hydration mismatch.
Pass it in as a build argument instead. In the multi-stage Dockerfile further down, the builder stage gets two lines:
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
+ARG NEXT_PUBLIC_API_URL
+ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run builddocker build --build-arg NEXT_PUBLIC_API_URL=https://api.staging.example.com -t my-next-app:staging .If you forget --build-arg, the ENV line sets the variable to an empty string, which Next inlines as "", so ?? fallbacks like the one above never fire. Use || for defaults, or fail the build early with RUN test -n "$NEXT_PUBLIC_API_URL".
With Compose, the equivalent is args: under build::
services:
web:
build:
context: .
args:
NEXT_PUBLIC_API_URL: https://api.staging.example.com
ports:
- "3000:3000"That means one image per environment. If that's a problem, drop the prefix and read a normal variable on the server at request time, for example in a dynamic server component that passes it down as a prop.
Warning: Build args are recorded in the image's build history, and
NEXT_PUBLIC_values end up in JavaScript that anyone can download. Never pass secrets this way.
A production Dockerfile with standalone output
With output: "standalone", next build traces the files the server needs and copies them, with a minimal server.js, into .next/standalone, so the runtime image no longer needs the full node_modules. In next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
};
export default nextConfig;A CommonJS next.config.js uses module.exports = { output: "standalone" } instead.
# syntax=docker/dockerfile:1
FROM node:20-bookworm-slim AS base
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
# 1. Install dependencies from the lockfile, inside Linux.
FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci
# 2. Build the app. Public env vars are baked in here.
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run build
# 3. Run only what the standalone output needs, as a non-root user.
FROM base AS runner
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
CMD ["node", "server.js"]docker build --build-arg NEXT_PUBLIC_API_URL=https://api.example.com -t my-next-app .
docker run --rm -p 3000:3000 my-next-appDetails that are easy to get wrong:
- Static files are not in the standalone folder. Copy
.next/staticandpublicseparately, to those exact paths, or pages lose CSS, JavaScript and images. - No public folder, no COPY. Without a
publicdirectory, remove that line or create the folder;COPYfails on a missing source. - Non-root user. The official Node images ship a
nodeuser.--chown=node:nodematters because Next.js writes its cache under.next/cacheat runtime. - The health check depends on
HOSTNAME=0.0.0.0. It calls127.0.0.1inside the container, exactly what Docker's ownHOSTNAMEbreaks, and readsPORT, so a run-time-e PORT=8080still passes. Slim images lackcurl, hence Node's built-infetch(Node 18+). Kubernetes ignoresHEALTHCHECKfor its own probes. - Images in standalone mode. In Next.js 14, standalone image optimisation needs
sharpas a dependency (Next.js logs an error without it);npm ciinside the image gets the Linux build. - Monorepos.
server.jslands in a subfolder of.next/standalonemirroring your repo layout, so adjust the paths.
CRLF line endings break shell scripts
The last classic is a shell entrypoint script that runs setup before the server starts:
#!/bin/sh
set -e
echo "Starting with NODE_ENV=${NODE_ENV}"
exec "$@"If Git on Windows converts line endings (core.autocrlf=true), this file is checked out with CRLF endings and COPY puts it into the image as-is. Linux then reads the first line as naming the interpreter /bin/sh plus an invisible carriage return, which doesn't exist. Depending on how it is started, you get errors like these:
exec /usr/local/bin/entrypoint.sh: no such file or directory
/bin/sh^M: bad interpreter: No such file or directory
set: Illegal option -The first is the confusing one: the file exists, but the interpreter named in it does not. The bug survives until deployment because Windows tools are forgiving; a CRLF copy of this script ran fine when I tried it in Git Bash. file and cat -A show what is really there:
file entrypoint.sh
cat -A entrypoint.shentrypoint.sh: POSIX shell script, ASCII text executable, with CRLF line terminators
#!/bin/sh^M$
set -e^M$
^M$
echo "Starting with NODE_ENV=${NODE_ENV}"^M$
^M$
exec "$@"^M$Each ^M is a carriage return.
The real fix is a .gitattributes at the repository root that forces LF for shell scripts, whatever anyone's Git settings:
* text=auto
*.sh text eol=lfThen normalize what's committed and refresh your copy of the script:
git add .gitattributes
git add --renormalize .
git commit -m "Normalize line endings for shell scripts"
rm docker/entrypoint.sh
git checkout -- docker/entrypoint.shBecause of * text=auto, this may touch many files; review git status before committing, or drop that line if you only want to fix scripts.
As a safety net, strip carriage returns and set the executable bit in the Dockerfile too. Git on Windows (where core.fileMode is false) usually commits scripts without that bit, so Linux CI checkouts lack it and the container fails with permission denied; you can also record it in Git with git update-index --chmod=+x docker/entrypoint.sh.
Put these lines in the runner stage before USER node, because sed -i needs root to rewrite files in /usr/local/bin:
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN sed -i 's/\r$//' /usr/local/bin/entrypoint.sh
USER node
EXPOSE 3000
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["node", "server.js"]COPY --chmod needs BuildKit, the default builder in recent Docker versions; on older setups, use a separate RUN chmod +x.
Checklist
- The server binds to
0.0.0.0, notlocalhost; the standalone image setsENV HOSTNAME=0.0.0.0andENV PORT. - The port is published with
-p host:container, matching the app's port on the container side. .dockerignoreexcludesnode_modules,.next,.gitand local env files.- Dependencies are installed with
npm ciinside the image from a committed lockfile, on the same base image family as the runtime (glibc or musl). - The image architecture matches the server: check with
docker image inspect, build with--platformorbuildx. - Compose dev setups use anonymous volumes for
/app/node_modulesand/app/.next, renewed after dependency changes. - Hot reload on Windows or macOS uses
WATCHPACK_POLLING=true, or the code lives in the WSL 2 filesystem. - Every
NEXT_PUBLIC_variable is a build arg, and none are secrets. - The production image uses
output: "standalone", copies.next/staticandpublic, and runs as thenodeuser. - Shell scripts are LF (
*.sh text eol=lfin.gitattributes) and executable.