Next.js standalone output is one config line, output: 'standalone', that makes next build write .next/standalone: a server.js plus only the node_modules files your routes were traced to need. It leaves out public and .next/static, so you copy both in, start it with node server.js, and set PORT and HOSTNAME yourself.
We built a small App Router app on Next.js 16.4.6, where Turbopack is the default builder, and ran everything below on Node 24.12.0 and Docker 27.3.1.
What does Next.js standalone output put in the folder?
Ours held server.js, package.json, a .next directory with the server build, and a node_modules with 12 top-level entries. On macOS, du -sh reported 51M for the whole folder against 337M for the project’s node_modules. The output docs describe how the files are chosen: the build statically analyses import, require and fs usage to work out what each page might load.
The generated server.js is 37 lines long. It sets NODE_ENV to production, calls process.chdir(__dirname), and takes its address from two variables:
const currentPort = parseInt(process.env.PORT, 10) || 3000
const hostname = process.env.HOSTNAME || '0.0.0.0'
It also carries your whole Next.js config as a JSON literal, serialised at build time. The config file is not in the folder, and when we dropped an edited next.config.mjs next to server.js it was ignored. Config changes need a rebuild.
Why do CSS, JS and images return 404?
server.js serves public and .next/static only when they sit beside it, and the build does not put them there. The docs give the reason: these “should ideally be handled by a CDN instead”.
Straight after the build, our server returned 200 for the page, 404 for the stylesheet that page linked, and 404 for /logo.svg. The server log printed nothing for either 404. Two copies fix it:
npm run build
cp -r public .next/standalone/
cp -r .next/static .next/standalone/.next/
node smoke.mjs .next/standalone /logo.svg
The last line is a check we wrote for this post. It starts the built server, requests the page, the first /_next/static URL in its HTML and one file from public, and exits 1 unless all three return 200.
// smoke.mjs - usage: node smoke.mjs .next/standalone /logo.svg
import { spawn } from 'node:child_process';
import path from 'node:path';
const [dir = '.next/standalone', publicFile = '/favicon.ico'] = process.argv.slice(2);
const port = 4310;
const origin = `http://127.0.0.1:${port}`;
const server = spawn(process.execPath, ['server.js'], {
cwd: path.resolve(dir),
env: { ...process.env, PORT: String(port), HOSTNAME: '127.0.0.1' },
stdio: 'inherit',
});
async function firstResponse() {
for (let attempt = 0; attempt < 50; attempt += 1) {
try {
return await fetch(origin);
} catch {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
throw new Error('server.js did not start listening');
}
let failed = false;
try {
const page = await firstResponse();
const html = await page.text();
const asset = html.match(/\/_next\/static\/[^"']+/)?.[0] ?? '/_next/static/missing';
const results = [['/', page.status]];
for (const url of [asset, publicFile]) {
results.push([url, (await fetch(origin + url)).status]);
}
for (const [url, status] of results) {
console.log(status, url);
if (status !== 200) failed = true;
}
} catch (error) {
console.error(error.message);
failed = true;
} finally {
server.kill('SIGTERM');
}
process.exit(failed ? 1 : 0);
Run before the copies, it exits 1 on the two 404s above. Run after them, it prints three 200s. A Dockerfile that forgets one of the COPY lines gives you the first result, so run the check in CI against the folder you are about to ship.
Why does localhost refuse connections inside the container?
server.js binds to whatever HOSTNAME holds, and Docker sets that variable in every Linux container to “The hostname associated with the container”. By default that is the container ID.
We built the image below with and without its ENV HOSTNAME line. With it, a request to 127.0.0.1:3000 from inside the container returned 200. Without it, HOSTNAME was 291b07c9540a, the same request failed with ECONNREFUSED, and the published port still answered 200 from the host. The site looks healthy from outside, and a HEALTHCHECK that requests localhost inside the container would be refused the same way.
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
FROM node:24-slim AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:24-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
COPY --from=builder --chown=node:node /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"]
This is the official with-docker example cut down to npm. Add a .dockerignore listing node_modules, .next, .git and .env*. Keep the exec-form CMD so that SIGTERM goes to Node and not to a shell; our notes on draining a Node server on SIGTERM cover what shell form does to signals.
Which files does the trace miss, and when does it copy too much?
File reads are traced along with imports. One of our routes read from path.join(process.cwd(), 'data', ...) with a .json file name built from the URL, and the build copied both JSON files in data without being told to. A text file in the same folder stayed behind.
That works because the folder name is a literal. We changed another route to take its folder from an environment variable:
const dir = path.resolve(process.env.TEMPLATE_DIR ?? 'templates');
The Turbopack build warned “Dynamic filesystem access causes tracing of the whole project”, and the standalone folder gained app/ with our source, next.config.mjs, package-lock.json, the Dockerfile and public. The same code under next build --webpack printed no warning and failed the other way: templates was left out and the route returned 500 with ENOENT.
The warning’s first suggestion is to scope the path to a fixed subfolder. When the folder has to be configurable, it offers an opt-out comment, after which you list the files yourself:
// app/api/template/[name]/route.js
import { readFile } from 'node:fs/promises';
import path from 'node:path';
const dir = path.resolve(/*turbopackIgnore: true*/ process.env.TEMPLATE_DIR ?? 'templates');
export async function GET(_request, { params }) {
const { name } = await params;
if (!/^[a-z0-9-]+$/.test(name)) return new Response('Not found', { status: 404 });
const file = path.join(/*turbopackIgnore: true*/ dir, `${name}.json`);
return Response.json(JSON.parse(await readFile(file, 'utf8')));
}
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
outputFileTracingIncludes: {
'/api/template/*': ['./templates/**/*.json'],
},
};
export default nextConfig;
Both comments were needed. With only the first, the warning stopped but the path.join below it still pulled package.json and package-lock.json into the trace. With both comments and no include, the route returned 500 until the outputFileTracingIncludes entry went in. Its keys are route globs matched with picomatch, and its values are globs resolved from the project root. The docs add that it does not affect Edge runtime routes or fully static pages.
Where does server.js go in a monorepo?
Under the app’s own path. In an npm workspaces repo with the app at apps/web, Next.js found the root lockfile and set the tracing root to the repo root with no config from us. The build wrote apps/web/.next/standalone/apps/web/server.js, with node_modules at the top of the standalone folder.
The copy targets move with it. public and .next/static copied to the top of the folder gave the same 404s as before. Copied into .next/standalone/apps/web/ they were served, and the container command becomes node apps/web/server.js. If the detection picks the wrong root, set outputFileTracingRoot yourself.
Do .env files end up in the image?
Two of them can. The output docs say that when the build loads .env or .env.production, standalone output “includes a copy of it in .next/standalone”. Ours had .env after the build and not .env.local.
At runtime the copy is a fallback. A route reading API_BASE returned the .env value by default, and a different one when we set the variable on the command that starts the server. A variable that existed only in .env.local came back null.
So a committed .env ships inside the artefact, and outputFileTracingExcludes does not remove it. Keep secrets out of those two files, or keep the files out of the build context, which is what .env* in .dockerignore does.
What changes when you run more than one instance?
We did not test this part; it comes from the self-hosting guide. Run one build everywhere instead of rebuilding per environment, because the build ID and the Server Functions encryption key are generated per build, and a mismatch between instances shows up as “Failed to find Server Action”. If you must rebuild, pin them with generateBuildId and NEXT_SERVER_ACTIONS_ENCRYPTION_KEY. Set deploymentId so a browser holding the old release reloads during a rollout. The cache for ISR pages sits in each instance’s memory and on its disk until you supply a cacheHandler.
What we would do
Use standalone output for any container deploy. Put the HOSTNAME line and the smoke check in from the first commit, and treat the “whole project” warning as a failed build, since it put our source and a lockfile into the folder we were about to ship. Keep file reads under a literal folder so the trace can see them.
Skip it when a platform’s adapter builds the app for you, as on Vercel, or on Cloudflare, which our OpenNext and vinext comparison covers. A site with no server-rendered routes has no Node process to run at all, so output: 'export' and a static host is less to look after.
We build and host Next.js apps for clients, in containers as well as on Vercel. If your image is carrying files it should not, or a deploy keeps losing its assets, our Next.js development work covers the pipeline as well as the app.