Package One Image, Deploy It Anywhere
Updated
IntermediateWhat you'll learn
~30 min- Produce Next.js standalone output and copy the static assets and public files that it leaves out
- Build one container image and identify the release by its digest (the content hash the registry assigns when you push), not by a tag
- Choose the platform seam implementation with the PLATFORM environment variable, so the same image runs on a laptop and on any cloud lesson's host
- Keep settings out of the image: identifiers arrive as settings and secrets come from the platform's secret store
What you ship
You will turn the app into one container image and run it two ways: on your laptop against the local stack from Lesson 8, and, in your platform lesson, on a cloud’s container host. The image is the same bytes both times. What changes is a handful of settings and one environment variable, PLATFORM, which picks the platform seam implementation (the one interface the core code uses to ask “who signs users in, where is the database credential, where do secrets live”, with one implementation per platform).
The same steps become the pipeline stages in Lesson 19; doing them once by hand shows you what the pipeline automates. The cloud half, the registry and host for each platform, is in the platform lessons, linked from the table.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| How code reaches the host | A container image in a private registry the agency controls | 34: App Service for Containers + Azure Container Registry · 35: ECS Fargate + ECR (App Runner was not in the GovCloud endpoint table read for this module) · 36: Cloud Run + Artifact Registry | Whether your boundary allows a container host |
| What “release” means | The image digest, recorded at push and deployed by name@sha256:... | 34–36: each host’s deploy command takes the digest-qualified reference | Who may re-tag or delete an image |
| Where config comes from | Identifiers as plain settings; secrets from the platform’s secret store at runtime | 34: Key Vault · 35: Secrets Manager · 36: Secret Manager | Rotation owner for each secret |
| How a deploy is judged | A health URL answered by the app itself | 34–36: the host’s health-check setting | What failure restarts the container |
Standalone output
Next.js can emit a self-contained server: output: "standalone" copies only the files the app needs, with a server.js entry point, into .next/standalone. Here is the reference next.config.ts your agent writes:
import type { NextConfig } from "next";
const config: NextConfig = { output: "standalone",};
export default config;The standalone folder deliberately leaves two things out: the built static assets in .next/static and your public folder. The server will start without them and every stylesheet, script and image will 404. Copying them in is the static copy; in a container you do it in the Dockerfile below.
The Dockerfile, and the error behind its first stage
A common first draft installs only production dependencies, to keep the image small, and then builds. That draft fails. This build output was reproduced for this module on the pinned stack with a fresh Next.js scaffold:
> Build error occurredError: Turbopack build failed with 1 error:./app/globals.cssError: Error evaluating Node.js codeError: Cannot find module '@tailwindcss/turbopack'The cause is npm ci --omit=dev ahead of npm run build. The build tooling (the Tailwind loader for Turbopack, and TypeScript) lives in devDependencies, so a production-only install does not have it. The fix is to install everything in the stage that builds, and to leave the dev tools out of the stage that runs. Standalone output copies only the runtime files the app needs, so the final image needs no install at all. In the same reproduction, a build with a full install exited 0, and the standalone server started and answered HTTP 200.
REFERENCE CONFIG Dockerfile: two-stage standalone build running as the non-root node user open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
# DockerfileFROM node:26-slim AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run build
FROM node:26-slim AS runnerWORKDIR /appENV NODE_ENV=production PORT=8080 HOSTNAME=0.0.0.0COPY --from=builder --chown=node:node /app/.next/standalone ./COPY --from=builder --chown=node:node /app/.next/static ./.next/staticCOPY --from=builder --chown=node:node /app/public ./publicUSER nodeEXPOSE 8080CMD ["node", "server.js"]Four details, each deliberate:
- Same base in both stages. Native modules such as the image optimizer’s sharp binaries are built for a C library. Mixing a glibc builder with a musl runtime (an Alpine image) can break them; this lesson did not test that combination.
- Non-root. The official Node images include a
nodeuser.USER nodemakes a container escape start from an unprivileged account. - Port 8080, host 0.0.0.0. The standalone server listens on
PORT; binding to all interfaces is required for a host’s proxy to reach it. Each platform lesson tells its host which port that is. - The tag matches the platform map. One Node major appears in
engines.node,.nvmrc, this Dockerfile and the pipeline’s Node setup; the pin and the fallback for when your base image or build agent does not ship the newest line are in the table in Lesson 2.
The reproduction ran with a different Node line than the one pinned today, and it did not run docker build. Tags for the pinned Node major on your registry mirror, and support for it on your platform’s container host and build agents, are unconfirmed. Check them in your own environment before you copy this file.
Plan the change with your agent
This task touches five files and a running container, so open your tool, switch to Plan mode inside the session (Shift+Tab, /plan, or the desktop app’s mode picker), and approve the plan before anything is written. In your tool of choice:
- Claude Code:
claude, then Shift+Tab or/plan - Codex:
codex, then/planor Shift+Tab (codex --sandbox read-onlywhen read-only must be enforced) - Antigravity:
agy, then Shift+Tab or/plan - Copilot:
copilot, then Shift+Tab or/plan
Lesson 2 holds the dated four-tool table; check it before you copy a spelling. Ask your agent:
Read next.config.ts and src/platform/index.ts, and plan a multi-stage Dockerfile using Next.js standalone output plus a liveness health endpoint that runs locally against our container stack. Ask anything unclear first.What to check in the plan before you approve
next.config.tssetsoutput: "standalone"and.dockerignoreexcludesnode_modules,.next,.git, and.env*.- The multi-stage
Dockerfileuses the pinned Node base image tag from Lesson 2 in both stages, runs a fullnpm ciandnpm run buildinbuilder, copies.next/standalone,.next/static, andpublicintorunner, setsNODE_ENV=production,PORT=8080, andHOSTNAME=0.0.0.0, and runsnode server.jsas the non-rootnodeuser. src/app/api/health/route.tswrapsGETinpublicRoute()and returns200{ status: "ok" }without touching the database.- No password, client secret, connection string, or baked-in
PLATFORMvalue appears in the image orDockerfile.
If the first plan uses npm ci --omit=dev in the builder stage or forgets .next/static, nudge it before approving:
Run a full npm ci in the builder stage so devDependencies are present, and copy .next/static into the runner.Approving a plan is a decision, so read it as you would a PR: does it touch only the places you named, and does it run anything that reaches outside your machine? The agent proposes; you approve; then it runs the lesson’s checks.
One image, one variable: PLATFORM
The core code never asks which cloud it is on. It imports the seam types and calls getPlatform(), and a single file decides which implementation answers. This is that file, from the runnable reference:
// src/platform/index.ts (excerpt)const loaders: Record<string, () => Promise<Platform>> = { local: async () => localPlatform, azure: () => import('./azure/index.ts').then((m) => m.azurePlatform), // lesson 34 aws: () => import('./aws/index.ts').then((m) => m.awsPlatform), // lesson 35 google: () => import('./google/index.ts').then((m) => m.googlePlatform), // lesson 36};// ...export async function getPlatform(name = process.env.PLATFORM): Promise<Platform> { const load = name ? loaders[name] : undefined; if (!load) throw new Error(`PLATFORM must be one of: ${Object.keys(loaders).join(', ')} (got ${name ?? 'nothing'})`); return load();}Two properties matter for packaging:
- An unknown value refuses to guess.
PLATFORM=mainframe, or nothing at all, throws and names the allowed values. A deployment that forgot the setting fails loudly instead of quietly running the local implementation in a cloud. - The platform lessons add entries, not branches. The AWS and Google lines are commented in the reference until lessons 35 and 36 supply their implementations. Adding a platform never edits the core.
What the seam hands the core, from the same reference:
// src/platform/types.ts (excerpt)export interface Platform { name: 'local' | 'azure' | 'aws' | 'google'; identity: Identity; db: { target: DbTarget; auth: DbAuth }; secrets: { get(name: string): Promise<string> }; telemetry: { start(serviceName: string): Promise<void> };}Settings come from the platform, not the image
The image is built once and carries no environment. Three kinds of value reach the running container, and none of them is baked in:
| Kind | Examples | How it arrives |
|---|---|---|
| Plain setting | PLATFORM, NODE_ENV, PORT, OTEL_EXPORTER_OTLP_ENDPOINT | Set on the host (or -e on a laptop); not secret |
| Identifier | The identity provider’s issuer and client id | Set on the host; the local implementation reads OIDC_ISSUER and OIDC_CLIENT_ID, and each platform lesson names its own |
| Secret | The sign-in client secret, the database credential | Fetched at runtime with platform.secrets.get(name); the seam holds the secret’s name, never its value |
Lesson 3 already reads the client secret this way: platform.identity.clientSecretName names it, and platform.secrets.get fetches it. So no environment variable in the image or on the host holds a secret value. How each host injects or fetches the secret, and who rotates it, is the platform lesson’s job: Key Vault in 34, Secrets Manager in 35, Secret Manager in 36.
Deploy it locally
The local deploy is the same image run against the local stack from Lesson 8: SQL Server on 127.0.0.1:14330, the mock identity provider on :8080, the collector on :4318. The local implementation reads its generated secrets from a directory outside the repository, so the container gets that directory read-only and runs as your user:
IMAGE=platform-app:localdocker build -t "$IMAGE" .
docker run --rm --name platform-app \ --network host --user "$(id -u):$(id -g)" \ -e PLATFORM=local -e PORT=3000 \ -e M14_SECRET_DIR=/run/m14 \ -v "${M14_SECRET_DIR:-$HOME/.config/m14-reference}:/run/m14:ro" \ "$IMAGE"--network host lets the container’s localhost reach the three local services on a Linux or WSL2 Docker engine, and it also means the container’s port is a port on your machine: the mock identity provider already holds 8080, so the run sets PORT=3000. Docker Desktop on another operating system handles host networking differently, so check yours. These commands show the shape. The reference holds the seam, not a Next.js app, so this lesson did not run them end to end: run them on your first build and read the output.
In a platform lesson, the same image is pushed to that platform’s registry and the host’s deploy command is given the digest. Whatever the registry, the step that matters is identical: push, read the digest the registry reports, and release that.
docker push "$REGISTRY/platform-app:$(git rev-parse --short HEAD)"docker inspect --format '{{index .RepoDigests 0}}' "$REGISTRY/platform-app:$(git rev-parse --short HEAD)"# prints: <registry>/platform-app@sha256:<64 hex characters>A tag such as the commit id is a label you can re-push to point at different content; platform-app@sha256:... names exactly the bytes you pushed. Tag with the commit so people can read what is running, and deploy by the digest so what runs is what you pushed. Lesson 20 binds the SBOM and test evidence to that same digest.
A health endpoint that does not ask the database
Here is the reference liveness route your agent writes in src/app/api/health/route.ts:
import { NextResponse } from "next/server";import { publicRoute } from "@/lib/auth/with-permission";
export const GET = publicRoute("liveness probe, returns no data", async () => NextResponse.json({ status: "ok" }, { status: 200 }),);The endpoint says the process is alive and serving. It is wrapped in publicRoute (lesson 05) so the route-policy test sees an explicit, reasoned exception. Do not add a database check to it. If the host uses this path to decide whether to restart the container, a brief database outage would restart a healthy app in a loop. Put dependency checks on a separate readiness route that a dashboard reads. Each platform lesson shows where its host takes the health-check path.
See it in action
- Typed in the terminal:
claude - Mode:Plan mode (Shift+Tab)
- You type in the session: Plan the container image for this app: what changes in next.config.ts, the Dockerfile stages, and how we run it locally. Do not edit anything yet.
- The tool replies: Plan mode: I can read files and run read-only commands, and I will not edit anything until you approve. Files I will touch: next.config.ts add output: "standalone" Dockerfile two stages; builder runs full npm ci; runner copies standalone, static, public; USER node .dockerignore node_modules, .next, .git, .env* src/app/api/health/route.ts GET returns 200 { status: "ok" }, no database call Commands I will run after approval: docker build, docker run (local stack, PLATFORM=local), curl the health URL. I checked src/platform/index.ts: PLATFORM must be local or azure, so the run needs -e PLATFORM=local. I will not push the image anywhere. Approve this plan?
- You type in the session: Approved. Implement it, build, and run it against the local stack.
- The tool replies: Wrote the four files. The Dockerfile base tag matches the pin in the platform map. $ docker build -t platform-app:local . [builder 4/6] RUN npm ci [builder 5/6] RUN npm run build [runner 5/5] COPY --from=builder --chown=node:node /app/.next/static ./.next/static Successfully built. $ docker run --rm --name platform-app --network host --user 1000:1000 -e M14_SECRET_DIR=/run/m14 -v ~/.config/m14-reference:/run/m14:ro platform-app:local Error: PLATFORM must be one of: local, azure, aws, google (got nothing) The container exited. I left PLATFORM off the run command. That is the seam doing its job: it refused to guess.
- You type in the session: Fix the run command and check health.
- The tool replies: $ docker run -d --rm --name platform-app --network host --user 1000:1000 -e PLATFORM=local -e PORT=3000 -e M14_SECRET_DIR=/run/m14 -v ~/.config/m14-reference:/run/m14:ro platform-app:local $ curl -fsS http://localhost:3000/api/health {"status":"ok"} Healthy. I set PORT=3000 because the container shares the host network and the mock identity provider from the local stack already holds 8080. I have not pushed anything, so there is no registry digest yet; the image id is local only.
- You type in the session: Check that no secret ended up in the image.
- The tool replies: $ docker run --rm --entrypoint env platform-app:local | grep -i -E 'password|secret' || echo clean clean $ docker history --no-trunc platform-app:local | grep -i -E 'password|secret|PLATFORM=' || echo clean clean No secret value and no PLATFORM value in the image or its history. PLATFORM is supplied when the container starts, and the generated secrets stay in the mounted directory outside the repository.
Illustrative session; exact output varies by tool and agency configuration.
Prove it
Run these five checks against your local image build:
VERIFICATION COMMANDS Local container verification checks (health, static assets, non-root user, no baked secrets, and invalid PLATFORM refusal) open reference hide reference Run these checks in your terminal (or ask your workspace agent to run them against your image file and report each result).
# 1. The running app answers.curl -fsS "http://localhost:${PORT:-3000}/api/health" # pass: {"status":"ok"}
# 2. Static assets are served (the static copy happened). Expect 200.base="http://localhost:${PORT:-3000}"curl -s -o /dev/null -w "%{http_code}\n" "$base/$(curl -s "$base/" | grep -o '_next/static/[^"]*\.css' | head -1)"
# 3. The container runs as a non-root user. Expect a non-zero uid.docker run --rm --entrypoint id platform-app:local -u
# 4. No secret value is baked in. Expect: clean.docker run --rm --entrypoint env platform-app:local | grep -i -E 'password|secret' || echo clean
# 5. A wrong PLATFORM is refused. Expect the error to name the allowed values (it appears at startup# or on the first request that needs the platform, depending on where your app first calls getPlatform).docker run --rm -e PLATFORM=mainframe -e PORT=3000 platform-app:local 2>&1 | grep "PLATFORM must be one of"The reference has the same negative case as a test: with the local stack running, npm run test:env in gov-dev-reference-app includes a test where PLATFORM=mainframe fails with PLATFORM must be one of, and the run reports 6 tests passed.
Fail on purpose once: remove the COPY of .next/static from the Dockerfile, rebuild, and rerun check 2. The page loads and the stylesheet returns 404, which is the symptom of a missing static copy.
The container starts and /api/health returns 200, but the page has no styling and images are broken. What is the most likely cause?
A pipeline builds an image, pushes it with the tag 'build-412', and deploys 'name:build-412'. Someone re-pushes build-412 with different content. What would have prevented the surprise?
You deploy the image to a new cloud host and forget to set PLATFORM. What should happen?
Key takeaway
Standalone output plus the static copy gives you a small image. Build it once with a full install in the builder stage, run it as a non-root user, and identify the release by the digest the registry reports. One variable, PLATFORM, picks the seam implementation; identifiers arrive as settings and secrets come from the platform’s secret store, so nothing sensitive is in the image. Make the health endpoint independent of the database. Lesson 19 turns these steps into pipeline stages, and lessons 34 to 36 land the image on a cloud.
- LEADERSHIP DECISION
- Which registry and digest identify a release, and that images carry no secrets.
- PRACTITIONER ACTION
- Build once, run as non-root, and record the digest the registry reports.
- SUCCESS MEASURE
- Audit finding avoided: every deployed image traces to one digest and contains no credential.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided