Vibe coding with Claude Code course Β· Module 13: Twitch clone

The Locked Crate: a Next.js Container with Claude Code

11 min read
In this lesson9

The clone works on your machine. The bosun clones the repository on his laptop, installs the dependencies and runs the build, and a moment later sees an error you have never seen: he has a different version of Node.js and a different system. The server on which the clone is to run one day will have yet another. Every such difference is a reef the ship hits only in a foreign port. You need a crate that arrives everywhere in the same state. In the programmers' world it is called a container.

Three words to start with. An image is packed cargo: the system, Node.js, the dependencies and the built app. A container is a running image, fenced off from the rest of the computer. A Dockerfile is the recipe by which Docker builds the image step by step. You install Docker yourself, following the page docs.docker.com/get-docker. The Next.js documentation advises working day to day with npm run dev on Mac and Windows, because it is faster, and leaving the container for production: you pack the crate for the voyage, not for work at the chart table.

What you will learn

  • order a container from Claude Code, starting from the current documentation, not from the agent's memory;
  • read a multi-stage Dockerfile and point at what ends up in the final image;
  • keep the .env file out of the repository and out of the image;
  • lock a destructive Docker command with a deny rule and know where its protection ends;
  • say where bypassPermissions mode makes sense and where it never does.

Request for Claude Code

The agent knows Docker from texts written years ago, and examples on the web age faster than Node.js images. That is why the first sentence of the request tells it to read the current source, and the second to choose and justify the build mode. The step touches four files, so you start with a plan, as in lesson 1_6. You will run the Docker commands yourself, for a reason you will learn below.

Request for Claude Code:

/plan Containerize the app. First read the page
https://nextjs.org/docs/app/getting-started/deploying (the Docker section)
and the with-docker example it leads to, and write which build output
mode you choose and why. Then: a multi-stage Dockerfile
(dependencies, build, run) on an image of the current Node.js LTS,
.dockerignore and compose.yaml. Read environment variables from an
.env file that is in neither the repository nor the image.
Done when: npm run build creates .next/standalone/server.js.
Do not run docker commands, I will do that myself.

In the plan check one thing: the build output mode. If Claude does not name it or picks it without a reason, answer "No, keep planning" and ask about it directly.

What Claude wrote: standalone mode

The first change is the smallest and the most important. Open next.config.ts in Cursor, and you will see a new line at the start of the configuration:

// next.config.ts
const nextConfig: NextConfig = {
  output: "standalone",
  // the rest of the configuration unchanged
};

With this option npm run build gathers in the .next/standalone folder only the files needed to run the app, plus a small server, server.js. For us the folder took 41 MB, and the full node_modules 517 MB. The option does not change how the page looks or how npm run dev works. Without it the build passes too, but the .next/standalone folder simply does not exist: we checked, and the Dockerfile below would then have nothing to copy.

What Claude wrote: the Dockerfile stage by stage

Open Dockerfile. Every FROM starts a new stage, and the word after AS gives it a name. The final image is only the last stage; the earlier ones are like a workshop in the port that stays on land. The first two stages:

FROM node:26-slim AS base
WORKDIR /app

FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci

base picks the Node.js image and the working folder /app, and the following stages inherit both. The tag 26-slim is the current Node.js LTS (as of November 2026) in a slimmed-down variant. The Next.js example picks slim instead of alpine, because slim has the standard Linux system library and copes better with npm packages that have native parts. deps copies only the two files with the dependency list and runs npm ci, an install exactly according to package-lock.json. When you change a component and not the dependencies, Docker takes this step from its cache and does not install everything again.

The third stage builds the app:

FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

COPY --from=deps brings node_modules over from the previous stage, and COPY . . the whole project code. This is the heaviest stage: it has the full dependencies, the source code and the build output. Nothing from it reaches the final image except what the last stage points at, and that stage looks like this:

FROM base AS runner
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]

runner gets only the build output. server.js from standalone mode reads the port from the PORT variable, and the address from HOSTNAME. The value 0.0.0.0 means "listen on all the container's addresses", as in the Next.js example. EXPOSE only describes the port, it opens nothing. The lines easiest to miss are the ones with public and .next/static, because the standalone folder does not contain them. We ran server.js without them: the page answered 200, but the CSS file and the voyage film got 404.

What Claude wrote: .dockerignore and compose.yaml

COPY . . copies the whole project folder, the build context, except what .dockerignore excludes. Open that file and read it from the top:

node_modules
.next
.git
.env
.env*.local

node_modules and .next are created anew in the container anyway, and .git is history the image does not need. The last two lines matter most. The Next.js example warns that a variables file present in the context ends up, in standalone mode, in .next/standalone, and from there in the image, where anyone who pulls the image can read it.

Now compose.yaml. Docker Compose is a tool that, with one command, builds the image and runs the container with the ports and variables described in the file:

services:
  app:
    build: .
    ports:
      - "3000:3000"
    env_file: .env

build: . builds the image from the Dockerfile in this folder. "3000:3000" connects port 3000 of your computer with port 3000 of the container. env_file loads the variables from .env only when the container starts, so the values are neither in the repository (the .env* line in the .gitignore from create-next-app) nor in the image. The clone has no secrets yet, so create an empty .env; without it docker compose config answered us with env file ... not found. The older name docker-compose.yml works too, but the Docker documentation calls compose.yaml the default.

The file has no version key, which you see in old tutorials. The Compose documentation says it is obsolete and only informative. On a file with version: '3.8' the command docker compose config printed a warning for us that the attribute is obsolete and will be ignored (is obsolete, it will be ignored).

A lock on the crate: a deny rule for Docker

Docker has commands that clean up too much. According to the documentation, docker system prune -a removes all unused containers, networks, images and the build cache. It asks for confirmation, but the -f option skips the question. If images of other projects sit on your computer, after such a cleanup they are gone. You know the deny rule from lesson 8_4, where it locked .env. Ask Claude for a rule for Docker in .claude/settings.json, together with the rules for .env from that lesson:

{
  "permissions": {
    "deny": ["Bash(docker system prune *)", "Read(./.env)", "Read(./.env.*)"]
  }
}

The space before the asterisk makes the rule catch docker system prune with any options. The Claude Code documentation says deny rules block in every mode, including auto and bypassPermissions. Check it with the request "Run docker system prune -a": Claude Code will not run the command, and Claude will see a refusal caused by the rule. When you ask more generally, for example "clean up unused images", Claude may reach for docker image prune -a, which this rule does not know. So cleaning up stays your decision, in your own terminal.

The lock has its limits, though. The permissions documentation says plainly that a Bash rule matches the text of the command, so it is not a security boundary: the same command written differently, for example inside sh -c '...' or with the program's full path, slips past the rule. It is similar with Read(./.env). From lesson 8_4 you know it does not cover commands that read the file without naming it. For us docker compose config printed a value from .env in plain text, although the rule was in place. The output of a command run by Claude lands in the conversation, and that is why you run Docker yourself. Hard isolation comes only from the sandbox (/sandbox), which limits commands at the system level.

Where bypassPermissions makes sense

bypassPermissions mode from lesson 0_4 approves almost everything without asking. The Claude Code documentation intends it only for isolated environments: containers and virtual machines in which Claude cannot harm your computer. Watch out for a mix-up: the app container you have just built is not that place, because Claude Code does not work inside it. What is meant is a container in which Claude Code itself runs, for example a dev container, a development environment described by the file .devcontainer/devcontainer.json. The Claude Code documentation has a ready configuration for it. Even there Claude changes the project files you see on your disk and reaches wherever the container's network allows, and deny rules still work. On your own computer, outside such a container, you never turn bypassPermissions on.

Captain's review

  1. Secrets outside the crate. .env stands in .dockerignore, and git status does not show it.
  2. Light cargo. The runner stage has no COPY --from=deps or COPY . ., but it does have public and .next/static.
  3. Current Node.js. The image tag is the current LTS from nodejs.org, not a version from a tutorial years old, which the agent likes to type from memory.
  4. Compose without ballast. No version key and no passwords under environment.

A typical agent mistake is access data typed straight into the Compose file, for example DATABASE_URL=postgresql://captain:secret@db:5432/deck under environment, or a missing output: "standalone", which leaves the runner stage with nothing to copy. You run the test in your own terminal in Cursor: npm run build and ls .next/standalone/server.js, then docker compose config, which must not print warnings, and docker compose up --build. When the container is up, open localhost:3000: the page should have its styles, and /channel/captain-redbeard should play the voyage. You stop the container with the command docker compose down.

Next step

When the review passes, ask for a commit "Container: standalone, Dockerfile, compose and a deny rule". Then one small step that the Next.js example takes for security: the app in the container should not run as root, the system administrator.

Request for Claude Code:

Run the app in the runner stage as the node user, like the
with-docker example from the Next.js documentation. Show the Dockerfile diff.

In the diff look for three things from the example: the line USER node before CMD, the option --chown=node:node when copying files into runner, and a .next folder owned by that user, because the server writes its page cache there. The node image has such a user ready, so nobody has to create it. When the process is not root, a bug in the app gives less power over the container. In the editor below waits a captain's review in miniature: the agent's version of the Compose file and .dockerignore, and the checker will point out version, a password in the file and the missing .env.

Remember: a good crate has a lock, and a good captain knows which keys he hands to the agent and which he carries himself.

Code for this lesson: App.tsx
// The captain's review in miniature: a checker for the Compose file and .dockerignore
import { useState } from 'react';

interface Finding {
  ok: boolean;
  title: string;
  detail: string;
}

const AGENT_COMPOSE = [
  "version: '3.8'",
  'services:',
  '  app:',
  '    build: .',
  '    ports:',
  '      - "3000:3000"',
  '    environment:',
  '      - DATABASE_URL=postgresql://captain:secret@db:5432/deck',
].join('\n');

const AGENT_IGNORE = ['node_modules', '.next', '.git'].join('\n');

const GOOD_COMPOSE = [
  'services:',
  '  app:',
  '    build: .',
  '    ports:',
  '      - "3000:3000"',
  '    env_file: .env',
].join('\n');

const GOOD_IGNORE = ['node_modules', '.next', '.git', '.env', '.env*.local'].join('\n');

// Access data in the address (user:password@) or a variable with a secret's name and a value typed in
const CREDENTIALS_IN_URL = /:\/\/[^\s:/@]+:[^\s@]+@/;
const SECRET_VALUE = /(PASSWORD|SECRET|TOKEN|API_KEY)\s*[:=]\s*\S+/i;

function lines(text: string): string[] {
  return text.split('\n').map((line) => line.trim());
}

export function reviewCrate(compose: string, dockerignore: string): Finding[] {
  const findings: Finding[] = [];

  const hasVersion = /^\s*version\s*:/m.test(compose);
  findings.push({
    ok: !hasVersion,
    title: 'The version key',
    detail: hasVersion
      ? 'Obsolete: Compose ignores it and prints a warning. Remove this line.'
      : 'No version key, as the Compose documentation recommends.',
  });

  const leaked = compose.split('\n').find((line) => CREDENTIALS_IN_URL.test(line) || SECRET_VALUE.test(line));
  findings.push({
    ok: !leaked,
    title: 'Passwords in the file',
    detail: leaked
      ? 'This line travels with the repository to everyone who clones it: ' + leaked.trim() + '. Move the value to .env.'
      : 'The file contains no passwords or tokens.',
  });

  const usesEnvFile = /^\s*env_file\s*:/m.test(compose);
  findings.push({
    ok: usesEnvFile,
    title: 'Variables from .env',
    detail: usesEnvFile
      ? 'env_file loads the variables when the container starts, so the values are in neither the repository nor the image.'
      : 'No env_file: the variables have to be passed some other way, and it is tempting to type them straight into the file.',
  });

  const ignored = lines(dockerignore);
  const ignoresEnv = ignored.includes('.env') || ignored.includes('.env*');
  findings.push({
    ok: ignoresEnv,
    title: '.env in .dockerignore',
    detail: ignoresEnv
      ? 'COPY . . will skip .env, so the file will not end up in the image.'
      : 'COPY . . will copy .env along with the context, and standalone mode will carry it into the image.',
  });

  const port = compose.match(/-\s*"(\d+):(\d+)"/);
  findings.push({
    ok: Boolean(port),
    title: 'Port',
    detail: port
      ? 'Port ' + port[1] + ' of your computer leads to port ' + port[2] + ' in the container.'
      : 'No port mapping in quotes, for example "3000:3000".',
  });

  return findings;
}

export default function App() {
  const [compose, setCompose] = useState(AGENT_COMPOSE);
  const [dockerignore, setDockerignore] = useState(AGENT_IGNORE);
  const findings = reviewCrate(compose, dockerignore);
  const problems = findings.filter((f) => !f.ok).length;

  return (
    <div className="min-h-screen space-y-4 bg-zinc-950 p-4 text-zinc-100">
      <h1 className="text-xl font-bold">Captain's review: the crate</h1>
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={() => {
            setCompose(AGENT_COMPOSE);
            setDockerignore(AGENT_IGNORE);
          }}
          className="rounded bg-zinc-700 px-3 py-2 text-sm"
        >
          The agent's version
        </button>
        <button
          type="button"
          onClick={() => {
            setCompose(GOOD_COMPOSE);
            setDockerignore(GOOD_IGNORE);
          }}
          className="rounded bg-purple-600 px-3 py-2 text-sm font-semibold"
        >
          Version after the review
        </button>
      </div>
      <div className="grid gap-3 sm:grid-cols-2">
        <label className="block text-sm">
          compose.yaml
          <textarea
            value={compose}
            onChange={(e) => setCompose(e.target.value)}
            rows={9}
            spellCheck={false}
            className="mt-1 block w-full rounded bg-zinc-900 p-2 font-mono text-xs"
          />
        </label>
        <label className="block text-sm">
          .dockerignore
          <textarea
            value={dockerignore}
            onChange={(e) => setDockerignore(e.target.value)}
            rows={9}
            spellCheck={false}
            className="mt-1 block w-full rounded bg-zinc-900 p-2 font-mono text-xs"
          />
        </label>
      </div>
      <p role="status" className={problems ? 'font-semibold text-amber-400' : 'font-semibold text-emerald-400'}>
        {problems ? 'To fix: ' + problems : 'The crate is ready for the voyage'}
      </p>
      <ul className="space-y-2 text-sm">
        {findings.map((f) => (
          <li key={f.title} className="rounded border border-zinc-800 p-2">
            <strong className={f.ok ? 'text-emerald-400' : 'text-red-400'}>{f.ok ? 'OK' : 'Fix'}</strong> {f.title}
            <p className="text-zinc-400">{f.detail}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why do we containerize a Next.js app with Docker?

  2. 2. Which stage of the Dockerfile from the lesson has the full node_modules and source code, and which one gets only the build output?

Hands-on tasks in the game

  • Vertical ordering

    Order the Dockerfile stages from the top of the file:

  • Horizontal ordering

    Arrange the port mapping in compose.yaml (one line): "3000:3000"

  1. QuestionQuiz: why Docker
  2. QuestionQuiz: what ends up in the final image
  3. Put in orderSorting: multi-stage Dockerfile stages
  4. Put in orderSorting: compose port mapping

Useful articles