All articles
DockerNext.jsNode.jsDevOps

Next.js Works Locally but Breaks in Docker: How to Fix It

Why a Next.js or Node app that runs locally breaks in Docker, from localhost binding to native modules, arm64 images and CRLF, and how to fix each one.

Tushar Pachouri14 min read

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, localhost means the container itself. Bind to 0.0.0.0, set HOSTNAME=0.0.0.0 for the standalone server, and publish the port with -p.
  • Never copy your machine's node_modules into the image: add a .dockerignore and run npm ci inside it so native binaries (sharp, bcrypt, esbuild, SWC) are built for Linux.
  • Images built on Apple Silicon are arm64 by default. Use --platform linux/amd64 or docker buildx when the server is amd64.
  • In Compose dev setups, protect the image's node_modules with 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.

BOUND TO 127.0.0.1 browser localhost:3000 -p 3000:3000 eth0 container interface refused listen 127.0.0.1 loopback only BOUND TO 0.0.0.0 browser localhost:3000 -p 3000:3000 eth0 container interface accepted listen 0.0.0.0 every interface
Published ports arrive on eth0, so a server bound to 127.0.0.1 refuses them.

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:

JavaScript
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:

Terminal
HOST=127.0.0.1 node bind-demo.mjs
HOST=0.0.0.0 node bind-demo.mjs
Text
server bound to 127.0.0.1
loopback       connected
other address  ECONNREFUSED
server bound to 0.0.0.0
loopback       connected
other address  connected

Custom 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:

JavaScript
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:

Diff
   "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:

Dockerfile
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:

Terminal
# 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-app

Still stuck? Test inside the container. If this works and the browser doesn't, the bind address or port mapping is wrong:

Terminal
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 the linux-x64 runtime.
  • bcrypt and other node-gyp addons fail with invalid 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:

Dockerfile
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:

Text
node_modules
.next
.git
npm-debug.log*
.env*.local

Second, install dependencies inside the image from the lockfile:

Dockerfile
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-gnu is 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):

Text
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 error

exec 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:

Terminal
# 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

YAML
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "3000:3000"
    volumes:
      - .:/app

With a Dockerfile.dev like this:

Dockerfile
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:

YAML
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.

The more specific volume mounts override the bind mount for node_modules and .next.

One gotcha: Compose reuses anonymous volumes when recreating a container, so after a dependency change the old node_modules can return. Start fresh with:

Terminal
docker compose up --build --renew-anon-volumes

Hot 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:

TSX
"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.

BUILD TIME RUN TIME process.env.NEXT_PUBLIC_API_URL next build inlines it "https://api.example.com" a literal in the browser JS docker run -e NEXT_PUBLIC_API_URL too late browser bundle unchanged unset at build means undefined
NEXT_PUBLIC_ values are baked into the bundle at build time, so docker run -e cannot change them.

Pass it in as a build argument instead. In the multi-stage Dockerfile further down, the builder stage gets two lines:

Diff
 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
Terminal
docker 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::

YAML
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:

JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "standalone",
};

export default nextConfig;

A CommonJS next.config.js uses module.exports = { output: "standalone" } instead.

Dockerfile
# 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"]
Terminal
docker build --build-arg NEXT_PUBLIC_API_URL=https://api.example.com -t my-next-app .
docker run --rm -p 3000:3000 my-next-app

Details that are easy to get wrong:

  • Static files are not in the standalone folder. Copy .next/static and public separately, to those exact paths, or pages lose CSS, JavaScript and images.
  • No public folder, no COPY. Without a public directory, remove that line or create the folder; COPY fails on a missing source.
  • Non-root user. The official Node images ship a node user. --chown=node:node matters because Next.js writes its cache under .next/cache at runtime.
  • The health check depends on HOSTNAME=0.0.0.0. It calls 127.0.0.1 inside the container, exactly what Docker's own HOSTNAME breaks, and reads PORT, so a run-time -e PORT=8080 still passes. Slim images lack curl, hence Node's built-in fetch (Node 18+). Kubernetes ignores HEALTHCHECK for its own probes.
  • Images in standalone mode. In Next.js 14, standalone image optimisation needs sharp as a dependency (Next.js logs an error without it); npm ci inside the image gets the Linux build.
  • Monorepos. server.js lands in a subfolder of .next/standalone mirroring 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:

Terminal
#!/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:

Text
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:

Terminal
file entrypoint.sh
cat -A entrypoint.sh
Text
entrypoint.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
* text=auto
*.sh text eol=lf

Then normalize what's committed and refresh your copy of the script:

Terminal
git add .gitattributes
git add --renormalize .
git commit -m "Normalize line endings for shell scripts"
rm docker/entrypoint.sh
git checkout -- docker/entrypoint.sh

Because 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:

Dockerfile
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, not localhost; the standalone image sets ENV HOSTNAME=0.0.0.0 and ENV PORT.
  • The port is published with -p host:container, matching the app's port on the container side.
  • .dockerignore excludes node_modules, .next, .git and local env files.
  • Dependencies are installed with npm ci inside 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 --platform or buildx.
  • Compose dev setups use anonymous volumes for /app/node_modules and /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/static and public, and runs as the node user.
  • Shell scripts are LF (*.sh text eol=lf in .gitattributes) and executable.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch