Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Standalone in Docker: Missing CSS and sharp Module Errors

output standalone copies server.js only, so /_next/static and public are missing and every page renders unstyled. The image and copy fixes, plus the sharp native binding error.

~5 min readNext.js
#Next.js#Docker#Deployment#Debugging
3D illustration of a container box missing a CSS slab and a static folder beside a Next.js triangle node with a warning glyph

Introduction & Quick Summary

Symptom. You added output: "standalone" to next.config.ts to shrink the runtime image, and the container now serves HTML with no stylesheet: the browser requests /_next/static/css/…css and /_next/static/chunks/…js and receives 404, while localhost:3000 in development looks perfect. Sometimes the page renders but every image returns 500 with Error: Could not load the 'sharp' module using the linux-x64 runtime or Something went wrong installing the "sharp" module, and the container logs show ModuleNotFoundError: No module named 'sharp' style traces from next/image.

Cause. next build with output: "standalone" writes a self-contained server to .next/standalone: server.js, the traced node_modules for your server dependencies, and nothing else. It deliberately does not copy .next/static (the client CSS, JS chunks and fonts) and does not copy public/. Those are expected to be served by a CDN in the deployment model the Next.js team assumes, so a Docker image that copies only .next/standalone produces the 404s. The sharp failure is a second, unrelated packaging problem: sharp is an optional dependency with platform-specific binaries, so a node_modules tree installed on macOS, or under musl in an earlier build stage, cannot resolve its native binding inside a glibc runtime stage.

Fix. Copy three things into the runtime image at the same paths Next expects — .next/standalone as the app root, .next/static to ./.next/static, and public to ./public — then run node server.js instead of next start. Install production dependencies inside the target platform for the sharp layer, or use next build in the same base image so tracing picks up the correct optional package, and keep sharp listed in dependencies rather than devDependencies.

Core Mechanics, Signatures & Reproducible Setup

output: "standalone" changes two things: the build emits a runnable server, and tracing narrows node_modules to files actually imported. The emitted layout mirrors the repository root, not your project directory, which is the single most common source of "file exists but is 404":

code
.next/standalone/ ├── server.js # entry point: node server.js ├── package.json # minimal, no scripts ├── node_modules/ # traced runtime deps only └── .next/ ├── server/ # server chunks, route manifest └── required-server-files.json .next/static/ # NOT included — must be copied public/ # NOT included — must be copied

Minimal reproducer:

ts
// next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", // monorepos only: pin the tracing root to the repo root // outputFileTracingRoot: path.join(__dirname, "../../"), }; export default nextConfig;
dockerfile
# syntax=docker/dockerfile:1.7 FROM node:22-alpine AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM node:22-alpine AS build WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . RUN npm run build FROM node:22-alpine AS run WORKDIR /app ENV NODE_ENV=production ENV PORT=3000 ENV HOSTNAME=0.0.0.0 # 1) the traced server, 2) the static assets it expects, 3) public files COPY --from=build /app/.next/standalone ./ COPY --from=build /app/.next/static ./.next/static COPY --from=build /app/public ./public EXPOSE 3000 USER node CMD ["node", "server.js"]

Three details matter beyond copy order. HOSTNAME=0.0.0.0 is required: the standalone server binds to localhost if HOSTNAME is unset on some hosts, and a container that listens only on loopback refuses connections from the port mapping. server.js is not next start; it reads PORT, HOSTNAME and NEXT_PRIVATE_* variables, and next start is unavailable because the next CLI is not traced into the standalone tree. And .next/static has to land at ./.next/static relative to the app root, which is where server.js sits — copying it to /app/static or /app/.next/standalone/.next/static produces exactly the same 404s you started with.

For sharp, the reliable pattern is to install in the same image and platform as the runtime:

dockerfile
FROM node:22-bookworm-slim AS run WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends libvips42 \ && rm -rf /var/lib/apt/lists/* # keep sharp a regular dependency so tracing and npm ci agree RUN npm ci --omit=dev

Building on Apple Silicon for linux/amd64 needs --platform on every stage: sharp resolves @img/sharp-linux-x64 (glibc) or @img/sharp-linuxmusl-x64 (Alpine) at install time and never downloads the other later.

Key Comparison Table

ArtefactIn .next/standalone?Where it must go in the imageSymptom when missing
server.js + traced node_modulesYes/appContainer exits instantly
.next/static/** (CSS, JS, fonts)No/app/.next/staticUnstyled HTML, 404 on /_next/static/*
public/**No/app/publicMissing favicon, og-image, robots.txt 404
.next/cache (ISR output)Nomount if you need ISR persistenceRe-render on every request
next CLI (next start)Nonot neededsh: next: not found
sharp native bindingOnly if traceddependencies, installed in-imageCould not load the 'sharp' module
Sharp strategyWorks across host→container?Image sizeNotes
npm ci inside runtime stageYesLargerResolves correct @img/* optional package
Copy host node_modulesNo (darwin/arm64 → linux)Small build cacheBinding mismatch errors at first image request
--os=linux --cpu=x64 --libc=musl flagsPartlySmallMust match base image libc exactly
images: { unoptimized: true }YesSmallestNo resizing/AVIF; browsers download originals
External loader (Cloudinary, imgix)YesSmallRemoves sharp from the critical path

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. CSS 404 only in the container, dev is fine

next dev serves assets from the build directory on disk, so nothing is missing. Confirm the runtime layout before touching the config:

bash
docker run --rm -it my-app sh -lc 'ls .next/static/css | head; ls public | head'

If .next/static is absent, the copy step is wrong. A Dockerfile written before output: "standalone" copies /app/.next only.

2. Static assets present but still 404 behind a reverse proxy

Next prefixes assets with /_next/. An nginx try_files or a Traefik rule that routes only / to the app, or strips a path prefix, breaks the exact URLs the HTML references. Either proxy the whole host or set assetPrefix so the emitted HTML points at the CDN:

ts
const nextConfig: NextConfig = { output: "standalone", assetPrefix: process.env.CDN_URL || undefined, };

3. Monorepo tracing puts everything in a nested folder

With a workspace package at apps/web, tracing writes apps/web/.next/standalone/apps/web/server.js plus a root node_modules. Copying standalone/apps/web alone loses the hoisted modules. Either copy the whole standalone tree and set the working directory, or pin the trace root:

ts
import path from "node:path"; const nextConfig: NextConfig = { output: "standalone", outputFileTracingRoot: path.join(import.meta.dirname, "../../"), };

Then the runtime image is WORKDIR /app, COPY --from=build /app/apps/web/.next/standalone ./, COPY --from=build /app/apps/web/.next/static ./.next/static.

4. Could not load the 'sharp' module using the linux-x64 runtime

The message names the runtime it tried. Read the whole trace: npm install suggestions at the bottom are for developers, not for a production image. Two checks settle it:

bash
docker run --rm my-app node -e "console.log(require('sharp').versions)" docker run --rm my-app ls node_modules/@img

No @img/* directory means the optional dependency was pruned, usually by npm ci --omit=optional, a .npmrc with optional=false, or a Yarn supportedArchitectures setting. If @img/sharp-linux-x64 exists but sharp.versions throws ELF or GLIBC_2.28 not found, the binary was built for a different libc — install inside the runtime stage.

5. Images work, then break after a base-image upgrade

node:22-alpine moves to a new Alpine minor and musl changes; a cached node_modules layer still holds the old binary. Add sharp to the same layer as the install and invalidate on the lockfile:

dockerfile
COPY package.json package-lock.json ./ RUN npm ci --omit=dev && npm rebuild sharp

6. ISR caches vanish and every request re-renders

Standalone mode writes ISR pages to .next/cache inside the container filesystem. With a read-only root or several replicas, each pod renders separately and cold starts hit the database. Mount a volume, or accept dynamic rendering explicitly:

yaml
services: web: image: my-app read_only: true tmpfs: - /tmp - /app/.next/cache

A tmpfs keeps the container read-only while allowing cache writes, and clears on restart.

Common Compilation/Runtime Mistakes & Version Gotchas

  • next start in the runtime stage. The CLI is not traced; the container crashes with sh: 1: next: not found. Use CMD ["node", "server.js"].
  • NODE_ENV=development in the runtime stage. server.js in a production build refuses to start or falls back to unoptimized behaviour. Set it explicitly, do not rely on the base image.
  • Bind address. Leaving HOSTNAME unset can bind to loopback; health checks fail while curl inside the container succeeds. Set HOSTNAME=0.0.0.0 and verify from outside with the cURL builder against http://127.0.0.1:3000/_next/static/….
  • Alpine vs Debian for sharp. Next.js 15 and 16 document sharp as required for next/image; on Alpine the musl build must be present. If libc alignment keeps breaking, use node:22-bookworm-slim.

Related tools. Check that the deployed assets actually answer with the right content type and cache header using the cURL builder, compare the emitted chunks between two builds with the text diff, and verify the traced package.json or lockfile hash with the hash generator before blaming the image.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.