Skip to content

Docker from scratch: what a container is, a cache-friendly Dockerfile, multi-stage, Compose and production

What a container really is, how to write a Dockerfile that uses the cache, multi-stage builds, volumes, Compose with healthchecks and the production details, with checked versions.

Ramon Gomes 11 min read Level: Beginner

Also available in: Español, Français, Português

"It works on my machine" is the line Docker came to retire. You package the app with the exact version of the runtime, the libraries and the configuration, and the same package runs on the laptop, in CI and on the server.

This article starts with what a container really is, moves through a well-written Dockerfile (the difference between a 2-second build and a 2-minute one), Compose for development, and ends with what to watch in production. Versions checked on November 21, 2026: Docker Engine 29.10.0, Docker Desktop 4.100.0 and Compose v5.8.0.

Port yard with stacks of colorful shipping containers and a gantry crane at sunset
The shipping container standardized cargo: the crane doesn't need to know what's inside.

What a Container Really Is

The Docker documentation puts it plainly: a container is a regular process on your computer, like a Node.js server, running in isolation.

The isolation comes from two Linux kernel features:

  • Namespaces make the process think it has the system to itself: its own process tree, network, file system and hostname. One container can't see another's processes.
  • cgroups limit and measure resource usage: how much memory, CPU and disk each group of processes can use.
Side-by-side comparison: three virtual machines with an app, operating system and kernel each above the hypervisor; three containers as processes on one shared kernel. Clocks and bars show VM booting and about 1 s for containers.
A VM boots a whole operating system. A container is a process already running on the kernel.

The difference from a VM is the kernel. Each virtual machine boots a full operating system with its own kernel. A container doesn't: it shares the host's kernel, so there's no system to boot. On Mac and Windows, Docker Desktop runs a Linux VM underneath, and the containers live inside it.

One consequence few people remember: namespace isolation is thinner than a VM's. Containers help a lot, but they're not as strong a security boundary as a separate machine.

Image, Container, Registry: The Vocabulary

Term What it is Analogy
Image Immutable, layered package with everything the app needs A frozen meal in a sealed container
Container An image running, with its own writable layer The meal heated up and served
Dockerfile The instruction file that produces the image The recipe
Registry Service that stores images (Docker Hub, GHCR, ECR) The restaurant freezer
Volume Storage managed by Docker that outlives the container The pantry, outside the meal container

You can start as many containers as you want from the same image, and what a container changes doesn't touch the image.

The First Dockerfile

A simple Node app:

dockerfile
FROM node:24-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 3000
CMD ["node", "src/index.js"]
sh
docker build -t my-api:1.0.0 .
docker run --rm -p 3000:3000 my-api:1.0.0

The . at the end of build is the context: the folder whose files the Dockerfile can copy. Create a .dockerignore from day one:

text
node_modules
.git
.env
dist

Without it, node_modules and .git go into the build (slow), and .env can end up inside the image (dangerous).

Layers and Cache: The Golden Rule

Each instruction that changes files creates a layer, a list of files added, changed or removed. The image is the stack of those layers. Docker caches each one and reuses it on the next build.

The rule in the docs is short: when a layer changes, every layer after it is rebuilt, even if the result would be the same.

A Dockerfile beside a stack of six layers. After src/index.js changes, COPY . . and CMD are rebuilt; the four lower layers stay cached.
Change one layer and every layer above it is rebuilt.

That's why the example copies package.json before everything else. Compare:

dockerfile
# Bad: any code change reinstalls the dependencies
COPY . .
RUN npm ci

# Good: dependencies are reinstalled only when package.json changes
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
Two Dockerfiles receive the same src/index.js change. With COPY . . before npm ci, dependencies are reinstalled; copying package*.json first keeps dependencies cached and rebuilds only COPY . . and CMD.
Same code, same change. Only the order of the lines is different.

The right order: what rarely changes on top (system, dependencies), what always changes at the bottom (your code).

Multi-stage: Build with Everything, Ship Only What's Needed

To compile TypeScript or build the front end, you need a compiler, dev dependencies and tools that are useless in production. A multi-stage build separates the two: one stage builds, the other receives only the result.

dockerfile
# Stage 1: build
FROM node:24 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

# Stage 2: only what runs in production
FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY package.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]
The build stage contains the compiler, devDependencies, source code and tools. Arrows carry only dist and production node_modules to the final image. Bars compare 1.87 GB and 401 MB in the Docker documentation example.
The build stage stays behind. Only the result travels.

In the official example in the Docker docs, a Node app with front end and back end dropped from 1.87 GB to 401 MB with this technique alone. A smaller image means faster downloads, faster deploys and less surface for vulnerabilities.

You can go further with minimal base images: Google's distroless images have no shell and no package manager, and Docker Hardened Images, free and open source since December 2025, already come non-root and with a signed SBOM.

The PID 1 Detail and docker stop

When you run docker stop, Docker sends a SIGTERM to the main process and waits (10 seconds by default) before killing it with SIGKILL. The app should use that time to finish in-flight requests and close connections.

That only works if the signal reaches the app. Two common mistakes block it:

  • CMD in shell form (CMD node src/index.js): the command runs inside /bin/sh -c, which doesn't forward signals. Use the JSON form: CMD ["node", "src/index.js"].
  • npm start as the command: npm sits in the middle and doesn't forward SIGTERM properly. The official Node image best practices say to call node directly.
Two docker stop flows: in shell form, sh as PID 1 holds SIGTERM and SIGKILL cuts requests after 10 s. In JSON form with --init, init forwards SIGTERM to Node, which finishes requests and exits with code 0.
Shell form holds the signal. JSON form delivers it to the app.

There's one more detail: Node wasn't built to run as PID 1, the initial process that Linux treats in a special way. The fix is docker run --init (or init: true in Compose), which puts a minimal process in front to forward signals and reap orphan processes.

Data: Volumes and Bind Mounts

Whatever the container writes to its own layer is gone when it's removed. To keep data:

Type How it works When to use it
Volume Area managed by Docker, outlives the container Database data in development, uploads
Bind mount Links a host folder to a container folder Source code in development
tmpfs In memory, never goes to disk Sensitive temporary files
sh
docker run -d -v pg-data:/var/lib/postgresql/data postgres:18

Compose: Several Containers at Once

A real app has an APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON., a database, Redis. Docker Compose describes everything in a compose.yaml file (the preferred name today; the version: field at the top is obsolete and only triggers a warning):

yaml
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://app:app@db:5432/app
    depends_on:
      db:
        condition: service_healthy
    init: true

  db:
    image: postgres:18
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    volumes:
      - pg-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 10s
      retries: 5
      start_period: 30s

volumes:
  pg-data:

Notice db:5432 in the URL: Compose creates its own network where containers find each other by service name. That doesn't happen on Docker's default network.

And notice the healthcheck. The docs are clear: without a condition, Compose waits for the container to be running, not ready. Postgres takes a few seconds to accept connections, and an API that starts first crashes with "connection refused".

Two Compose flows: without a healthcheck, the API tries to connect while the database starts and fails with connection refused. With pg_isready and service_healthy, the API waits for the database to become healthy, then connects.
Running isn't ready. The healthcheck says when the database accepts connections.

For day-to-day development, docker compose watch syncs saved code into the container or rebuilds when package.json changes.

Cartoon of a developer handing their own laptop, packed in a cardboard box with a note taped to it, to the operations team, while a colleague looks on in disbelief
It worked on my machine. So I shipped the machine.

Production: What Changes

Pin the version. The latest tag is just the name used when you don't specify one; it doesn't mean "stable" and can change at any time. Use explicit versions (node:24.11-slim) and, for full reproducibility, the digest (@sha256:...), with Dependabot or Renovate keeping it updated.

Don't run as root. The docs recommend a non-root USER whenever the service can run without privileges. The official Node image already ships with the node user.

Secrets don't go in the image. ARG and ENV are recorded in the image history (docker history shows them). If the build needs a token (to download a private package, for example), use a build secret:

dockerfile
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
sh
docker build --secret id=npmrc,src=$HOME/.npmrc .

At runtime, the secret comes from the platform's environment (injected variable, secrets manager), never from the Dockerfile.

Limit resources. By default, a container has no limit and can consume all the server's memory. Use --memory and --cpus (or deploy.resources.limits in Compose).

Scan the image. docker scout cves my-api:1.0.0 or trivy image my-api:1.0.0 list the known vulnerabilities in the packages inside it.

Watch the Docker Hub limit. Anonymous users can make 100 pulls every 6 hours per IP. In CI with shared runners, log in or use a mirror.

License: Is Docker Free?

Docker Engine, on Linux, is open source (Apache 2.0) and free for any use. Docker Desktop, the app for Mac and Windows, is free only for personal use, education, open source and companies with fewer than 250 employees and less than $10 million in annual revenue. Go past either limit and you need a subscription.

Compatible alternatives exist: Podman (6.2) runs the same images, because they all follow the open OCI standard, and there are options like Rancher Desktop and OrbStack for Mac.

Quick check

1. What's the essential difference between a container and a virtual machine?
Show answer

Answer: The container shares the host's kernel; the VM runs its own kernel

A container is an isolated process. There's no operating system to boot.

2. You changed one line of code. Why did npm ci run again?
Show answer

Answer: COPY . . comes before npm ci, and the change invalidated the layers after it

Copy only package.json and the lockfile before installing.

3. In Compose, what does depends_on without a condition guarantee?
Show answer

Answer: That the database is running, but not that it's ready

To wait for the database to be ready, use a healthcheck with condition: service_healthy.

Frequently Asked Questions

Docker or Podman?

If you're starting out, Docker, because of the amount of material out there. Podman runs the same images and is a good option where the Docker Desktop license is a burden.

Do I need Kubernetes?

Not to get started. Docker with Compose handles a single server very well. Kubernetes makes sense when there are many machines and services to orchestrate.

Alpine or slim?

Alpine is smaller, but it uses musl instead of glibc, which sometimes breaks native dependencies. slim (trimmed-down Debian) is the safer choice for Node and Python.

How do I see what's inside an image?

docker history my-api:1.0.0 shows the layers and the size of each. To explore the files, docker run --rm -it my-api:1.0.0 sh (if the image has a shell).

Can I use Docker in production without Kubernetes?

Yes. Platforms like Coolify, Render and Fly.io, and Compose itself on a server, run containers in production. The CI/CD article shows how to automate the build and the deploy.

References

Checked on November 21, 2026:

Source: https://ramongomessilva.com.br/blog/docker-from-scratch · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Docker from scratch: what a container is, a cache-friendly Dockerfile, multi-stage, Compose and production. Ramon Gomes, 1 dez. 2026. Disponível em: https://ramongomessilva.com.br/blog/docker-from-scratch. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, December 1). Docker from scratch: what a container is, a cache-friendly Dockerfile, multi-stage, Compose and production. Ramon Gomes. https://ramongomessilva.com.br/blog/docker-from-scratch

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026dockerfromscratch,
  author = {Gomes, Ramon},
  title = {{Docker from scratch: what a container is, a cache-friendly Dockerfile, multi-stage, Compose and production}},
  organization = {Ramon Gomes},
  year = {2026},
  month = dec,
  date = {2026-12-01},
  url = {https://ramongomessilva.com.br/blog/docker-from-scratch},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles