irfan@backend:~/portfolio
Email me
← cd ../blog

Docker / DevOps / Beginner

Docker from Zero: from your laptop to CI

A beginner Docker guide: images, a first Dockerfile, ports, the build cache, clean shutdown, small images, Compose, image scans and CI.

On this page
  1. Image, container and registry
  2. Why Node 24
  3. Your first Dockerfile
  4. The Dockerfile, line by line
  5. Build and run it
  6. The .dockerignore file
  7. Ports
  8. EXPOSE does not open anything
  9. Listen on 0.0.0.0, not localhost
  10. Read the port from PORT
  11. Run it in the background
  12. Layers and the build cache
  13. Deleting a file later does not shrink the image
  14. Keep npm's download cache between builds
  15. Comments go on their own line
  16. Exec form and PID 1
  17. What docker stop does
  18. Node as PID 1 needs a handler
  19. Shell form can hide the signal
  20. Multi-stage builds
  21. A three-stage Dockerfile
  22. Base images and users
  23. Choosing a base image
  24. Run as a non-root user
  25. Docker Compose
  26. The service name is the host name
  27. Scanning and build secrets
  28. Secrets in layers
  29. GitHub Actions build and push
  30. Scan before you push
  31. Tags: the SHA tag and lowercase names
  32. Pin actions to a commit SHA
  33. Recap

Your API runs fine on your laptop. Then it crashes on the server, because the server has a different Node version or a missing library. This post follows one small app, hello-api, from your laptop all the way to CI.

After this post you can:

  • write a Dockerfile for a Node API, build it, run it and open it in your browser
  • make rebuilds take seconds, stop the app cleanly, and ship a small image that does not run as root
  • run the API with Postgres in Compose, scan the image, and push it from GitHub Actions

Docker packs your app together with the exact Node version and files it needs, so it runs the same way everywhere. You need Docker Desktop (Mac or Windows) or Docker Engine (Linux), plus Node.js on your machine.

Image, container and registry#

Words you need:

  • Image: a read-only package with a small file system, a runtime (here Node) and your app. It does not run. It sits on disk.
  • Container: an image that is running. It is a normal process on your machine, but it sees only its own files.
  • Registry: a store for images. Docker Hub is the default one. GitHub has GHCR (ghcr.io), AWS has ECR, Google has Artifact Registry.
  • Tag: the part after the colon. In node:24-alpine, the tag is 24-alpine (Node 24 on Alpine Linux, a very small Linux).

Run this in your terminal:

docker run --rm node:24-alpine node -v

It prints a Node version, like v24.22.1. You did not install Node 24 for this. Three things happened in that one line:

  1. Docker pulled (downloaded) the image node:24-alpine from a registry.
  2. Docker started a container from that image.
  3. The container ran node -v, then stopped. --rm deleted it.

The downloaded image stays on disk, so the next run starts faster.

An image is like a class. A container is like an object made from that class. You can start many containers from one image, the same way you can call new User() many times.

The registry works like the npm registry, but for images:

npmDocker
npm registryDocker Hub, GHCR, ECR
npm installdocker pull
npm publishdocker push
a package versionan image tag

CI (continuous integration) is a server that builds and tests your code on every push. Follow hello-api from your code to production:

code-to-production
  1. docker build turns your Dockerfile and code into an image.
  2. On your laptop, docker run starts a container from that image.
  3. In a real deploy, CI pushes the image to a registry.
  4. The server pulls that same image.
  5. The server runs it as a container.
step 1 / 5
The image you tested is the exact image that runs in production. That is the main reason to use Docker.

Why Node 24#

Node 24 is an LTS line (long-term support, the versions meant for production). Node 26 becomes LTS on 28 October 2026, per the Node.js release schedule. After that date you can change 24 to 26 everywhere in this post.

quick-check

You start 3 containers from one image. How many images do you have?

quick-check

Which command downloads an image from a registry without running it?

Your first Dockerfile#

Words you need:

  • Dockerfile: a recipe. Docker reads it from top to bottom and builds an image.
  • package-lock.json: the file that locks the exact version of every package.
  • Dev packages: the ones under devDependencies in package.json, like test tools or TypeScript. You need them only while you develop.
  • Root: the admin user.
  • Build context: the folder Docker sends to the builder (the part of Docker that runs the Dockerfile steps).

Here is hello-api, a tiny Express API with one route, /health. The ECS and Cloud Run posts use this same app. Make a new folder called hello-api with two files.

package.json:

{
  "name": "hello-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^5.3.0"
  }
}

server.js:

import express from 'express';

const app = express();
const port = Number(process.env.PORT) || 3000;

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.listen(port, '0.0.0.0', () => {
  console.log(`listening on port ${port}`);
});

Run npm install once. It creates package-lock.json. The Dockerfile below needs it.

The Dockerfile, line by line#

Create a file named Dockerfile (no extension) in the same folder:

FROM node:24-alpine
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci --omit=dev

COPY . .

USER node
ENV PORT=3000
EXPOSE 3000
CMD ["node", "server.js"]
LineWhat it does
FROM node:24-alpinestart from an image that already has Node 24
WORKDIR /appwork in the /app folder inside the image, like cd /app
COPY package.json package-lock.json ./copy only the two package files first
RUN npm ci --omit=devinstall the exact versions from the lock file, without dev packages
COPY . .copy the rest of your code
USER noderun the app as the node user, not as root (the admin user)
ENV PORT=3000set a default value for the PORT variable
EXPOSE 3000a note that says "this app uses port 3000"
CMD ["node", "server.js"]the command that runs when the container starts

A few lines need a short reason:

  • RUN runs at build time. CMD runs at start time. npm ci happens once, when you build. node server.js happens every time a container starts.
  • npm ci, not npm install. npm ci installs exactly what package-lock.json says. It fails if the lock file is out of date. npm install can change the lock file. In a build, you want the same result every time.
  • Two COPY lines on purpose. Copying the package files before the code makes rebuilds much faster. The Layers and the build cache chapter shows why.
  • USER node. The official Node images come with a user called node. A bug in your app then does not give an attacker root inside the container. The Base images and users chapter covers this more.

Build and run it#

docker build -t hello-api .
docker run --rm -p 127.0.0.1:3000:3000 hello-api

-t hello-api gives the image a name. The . at the end is the build context. COPY can only see files in that folder. The Ports chapter explains -p.

Now open http://localhost:3000/health in your browser, or run:

curl http://localhost:3000/health

You get {"status":"ok"}. Press Ctrl+C to stop the container.

The .dockerignore file#

Your folder has node_modules, .git and an .env file with your passwords. What does COPY . . copy? Everything. Every file in the build context goes into the image unless you exclude it.

Create .dockerignore next to the Dockerfile. It works like .gitignore:

node_modules
npm-debug.log
.git
.env
.env.*
Dockerfile
.dockerignore
coverage
  • node_modules: your local packages may be built for macOS or Windows. The image installs its own with npm ci.
  • .git: big, and not needed to run the app.
  • .env and .env.*: secrets must never be baked into an image. Anyone who can pull the image can read every file in it.

The rule: if a file is not needed to build or run the app, exclude it. It costs nothing and makes builds faster and safer.

quick-check

Which line runs only once, while the image is built?

Quick check: you forgot .dockerignore, and your folder has an .env file with a database password. You push the image to a public registry. What is the problem?

Show answer

COPY . . copied .env into the image. Anyone who pulls the image can read the password. Deleting .env from your laptop later does not remove it from the pushed image. Change the password, add .dockerignore, and build again.

Ports#

Words you need:

  • Port: a number that says which program on a machine gets the network traffic. Your API listens on port 3000.
  • Host: your own machine, the one that runs Docker.
  • Publish a port: tell Docker to forward traffic from a port on the host into a port in the container.

Run the image without -p:

docker run --rm hello-api

The log says listening on port 3000. Now run curl http://localhost:3000/health in a second terminal. It fails:

curl: (7) Failed to connect to localhost port 3000 after 0 ms: Couldn't connect to server

The app is running. So what is wrong?

EXPOSE does not open anything#

A container has its own network. Port 3000 inside the container is not port 3000 on your laptop. EXPOSE 3000 does not connect them. The Dockerfile reference says it plainly: "The EXPOSE instruction doesn't actually publish the port." It is only a note for the person who runs the image.

The -p flag connects them. The format is -p HOST_ADDRESS:HOST_PORT:CONTAINER_PORT:

docker run --rm -p 127.0.0.1:8080:3000 hello-api
curl http://localhost:8080/health

Your laptop's port 8080 now forwards to port 3000 in the container.

Why 127.0.0.1: in front? A plain -p 8080:3000 publishes the port on every network address of your laptop. Then anyone on the same Wi-Fi can reach your app. 127.0.0.1 keeps it on your laptop only.

request-into-a-container
  1. curl sends a request to localhost:8080 on your laptop.
  2. Docker owns port 8080 because of -p 127.0.0.1:8080:3000.
  3. Docker forwards the request to port 3000 in the container.
  4. Express listens on 0.0.0.0:3000, so it accepts the request.
  5. The response goes back the same way: {"status":"ok"}
step 1 / 5
Without -p, step 2 never happens, so the request has nowhere to go.

Listen on 0.0.0.0, not localhost#

Look at this line in server.js again:

app.listen(port, '0.0.0.0', () => {

Inside a container, localhost (or 127.0.0.1) means "the container itself". Traffic that Docker forwards does not come from inside the container. It arrives on the container's network address. An app that listens only on localhost never sees it. curl then gets Empty reply from server.

0.0.0.0 means "every network address of this machine". So the forwarded traffic reaches your app. If you call listen(port) with no address, Node listens on every address too. The bug appears when your code or a framework sets localhost or 127.0.0.1 on purpose.

App listens onWorks on your laptop without DockerWorks inside a container with -p
localhost / 127.0.0.1yesno
0.0.0.0yesyes

Read the port from PORT#

const port = Number(process.env.PORT) || 3000;

This line reads the port from the PORT environment variable, with 3000 as the fallback. The platform that runs your container often picks the port. Google Cloud Run, for example, sets PORT (8080 by default) and sends traffic there. Test it like this:

docker run --rm -e PORT=8080 -p 127.0.0.1:8080:8080 hello-api

-e PORT=8080 sets the variable inside the container. The app now listens on 8080, so the last number in -p changes to 8080 too.

Run it in the background#

Ctrl+C is fine for a test. For longer runs, start the container in the background with -d (detached):

docker run -d --name api -p 127.0.0.1:3000:3000 hello-api
docker ps
docker logs api
docker exec -it api sh
docker stop api
docker rm api
  • docker ps lists running containers.
  • docker logs api shows what the app printed.
  • docker exec -it api sh opens a shell inside the running container, good for looking around. Type exit to leave.
  • docker stop api stops it. docker rm api deletes the stopped container. The image stays.
quick-check

Your Dockerfile has EXPOSE 3000. You run docker run hello-api. Can your browser open localhost:3000?

quick-check

Your app listens on 127.0.0.1:3000 and you run it with -p 127.0.0.1:3000:3000. curl gets Empty reply from server. Why?

Quick check: you run docker run --rm -e PORT=4000 -p 127.0.0.1:4000:3000 hello-api. Does curl localhost:4000/health work?

Show answer

No, curl gets Empty reply from server. -e PORT=4000 makes the app listen on 4000 inside the container. But -p 127.0.0.1:4000:3000 forwards to port 3000, where nothing listens. Use -p 127.0.0.1:4000:4000. The last number in -p must match the port the app listens on.

Layers and the build cache#

hello-api works. But change one line of code and the rebuild installs every package again. This chapter fixes that.

Words you need:

  • Layer: a saved snapshot of the files that one Dockerfile step added or changed. An image is a stack of layers.
  • Build cache: layers Docker saved from earlier builds, so it can skip steps that would give the same result.
  • Cache key: what Docker checks before it reuses a layer. It looks at the instruction, the layer below it, and the content of any copied files.

Here is a Dockerfile for hello-api, written the "obvious" way:

FROM node:24-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "server.js"]

Build it. Change one word in server.js and build again. Docker runs npm ci again, though no package changed. With a big app, that costs minutes on every code change.

If you know git, a layer is a lot like a commit: it stores only the changes on top of the one below. Docker checks the cache key of each step, from top to bottom. The first step that changed rebuilds, and so does every step after it.

cache-breaks-on-copy
  1. FROM node:24-alpine: same base image, reused.
  2. WORKDIR /app: same instruction, CACHED.
  3. COPY . .: server.js changed, so this layer is new.
  4. RUN npm ci: the layer below it changed, so it runs again.
step 1 / 4
CMD is not in the list. It only sets the start command, so it adds no files and no build step.

Now swap the order, like the Dockerfile in the Your first Dockerfile chapter:

FROM node:24-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]

Change server.js and build again. Now the build output says CACHED under npm ci, and only the last COPY runs.

So the rule is simple. Put the lines that change rarely at the top, and the lines that change often at the bottom. Packages change rarely. Code changes all day. So the package files and npm ci go first, and COPY . . goes last.

Deleting a file later does not shrink the image#

Layers never change. Deleting a file in a later step only hides it, and the file stays in the earlier layer. Download and clean up in one RUN. On a Debian-based image:

RUN apt-get update \
 && apt-get install -y --no-install-recommends curl \
 && rm -rf /var/lib/apt/lists/*

On Alpine, apk add --no-cache curl does the same. Secrets work the same way: a token you copy and later delete is still in the image. The Scanning and build secrets chapter shows the fix.

Keep npm's download cache between builds#

When package-lock.json does change, a cache mount makes npm ci faster. It keeps npm's download folder between builds, outside the image:

# syntax=docker/dockerfile:1
FROM node:24-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

The first line looks like a comment, but it is a parser directive. It tells Docker to use the latest stable version of the Dockerfile syntax. It only works at the very top of the file.

Comments go on their own line#

The Dockerfile reference says a # that is not at the start of a line "is treated as an argument". Try these two:

COPY . . # copy the code
USER node # drop root

The COPY line fails the build with lstat /#: no such file or directory. The USER line is worse. The build passes, then the container fails at start with unable to find user node # drop root. Put the comment on the line above:

# drop root
USER node
quick-check

You change only server.js. In the swapped Dockerfile (package files first), which step runs again?

Exec form and PID 1#

Stop the hello-api container and it hangs before it dies. Why?

Words you need:

  • Signal: a short message the operating system sends to a process. SIGTERM means "please stop now". SIGKILL means "you are stopped", and the process can't react to it.
  • PID 1: the first process in a container. It gets the signals that Docker sends.
  • Exec form and shell form: two ways to write CMD. Exec form is a JSON array. Shell form is a plain command line.

Run the image in the background and look at its processes:

docker run -d --name api -p 127.0.0.1:3000:3000 hello-api
docker top api

docker top lists the processes inside a container. There is one, node server.js. Now stop it:

docker stop api
docker inspect -f '{{.State.ExitCode}}' api
docker rm api

docker stop hangs until Docker's stop timeout ends (10 seconds by default). Then the exit code is 137. Your app never got to finish open requests or close connections.

What docker stop does#

Per the docker stop docs, Docker sends SIGTERM to the main process and waits. If the container still runs, Docker sends SIGKILL. Exit code 137 means "killed by SIGKILL" (128 + 9). ECS, Cloud Run and Kubernetes stop containers the same way.

Node as PID 1 needs a handler#

docker top shows host PID numbers. The process with no parent in the container is PID 1 inside it. PPID is the parent's PID. Here that process is Node, so the SIGTERM reached Node.

But the Node Docker best practices warn that Node "was not designed to run as PID 1". As PID 1, it does not stop on SIGTERM unless you add a handler:

import express from 'express';

const app = express();
const port = Number(process.env.PORT) || 3000;

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

const server = app.listen(port, '0.0.0.0', () => {
  console.log(`listening on port ${port}`);
});

process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing');
  server.close(() => process.exit(0));
});

server.close() stops new connections and waits for open requests to finish. Build again and run the same docker stop. It returns at once, with exit code 0.

graceful-shutdown
  1. You run docker stop api.
  2. Docker sends SIGTERM to PID 1, which is node.
  3. The SIGTERM handler calls server.close().
  4. Open requests finish, new ones are refused.
  5. Node exits with code 0, before Docker's 10-second wait ends.
step 1 / 5
Without the handler, step 3 never happens. Docker waits, then sends SIGKILL.

Shell form can hide the signal#

CMD ["node", "server.js"] is exec form. Docker starts node directly. CMD node server.js is shell form. Docker runs it as /bin/sh -c "node server.js".

Change two lines of the Dockerfile from the Your first Dockerfile chapter to build a shell form version on a Debian-based image:

FROM node:24-trixie-slim
CMD node server.js

Build and run it. Now docker top shows two processes:

UID     PID     PPID    C   STIME   TTY   TIME       CMD
1000    4148    4124    0   14:51   ?     00:00:00   /bin/sh -c node server.js
1000    4162    4148    7   14:51   ?     00:00:00   node server.js

The shell is PID 1, and Node is its child. docker stop sends SIGTERM to the shell, and the shell does not pass it on. Even with the handler, the app is killed with 137.

On node:24-alpine, the same shell form happens to work. Alpine's small shell replaces itself with node, so Node ends up as PID 1. Don't rely on that. Exec form works on every image.

quick-check

On node:24-trixie-slim, which CMD lets your SIGTERM handler run on docker stop?

Multi-stage builds#

The image still carries tools it never uses at runtime. Many Node APIs are written in TypeScript. You need the compiler and dev packages to build the app, but not to run it. A single-stage image ships them anyway.

Words you need:

  • Stage: one FROM block in a Dockerfile. A file with several FROM lines has several stages.
  • Multi-stage build: earlier stages build things, and the last stage copies in only the results. Only the last stage becomes your image.
  • Distroless: images from Google with only a language runtime (here Node) and the files it needs. They have no shell and no package manager.
  • ESM: ES modules, the import / export syntax. Node uses it when package.json has "type": "module".
  • Entrypoint: the fixed program that runs at start. Docker adds CMD after it.

A three-stage Dockerfile#

Say npm run build compiles src/ into dist/, and package.json has "type": "module" like hello-api:

# syntax=docker/dockerfile:1

# Stage 1: build with every tool
FROM node:24-trixie-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build

# Stage 2: production packages only
FROM node:24-trixie-slim AS prod-deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

# Stage 3: the image you ship
FROM gcr.io/distroless/nodejs24-debian13:nonroot
WORKDIR /app
ENV NODE_ENV=production
COPY package.json ./
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
CMD ["dist/server.js"]

Why is there no node in that last CMD? The distroless image already sets its entrypoint to Node. So the container runs node dist/server.js. It is still exec form, so the Exec form and PID 1 chapter still holds.

Each stage hands one thing to the last stage:

COPY --from=build and COPY --from=prod-deps take files out of the earlier stages. Nothing else from those stages gets in. Two more lines need a reason:

  • COPY package.json ./: Node reads "type": "module" from it. Without it, Node can't load the ESM code.
  • NODE_ENV=production: many Node libraries read this variable. Express, for example, stops showing error details to users when it is set.

hello-api has no build step. For it, drop the build stage and copy server.js instead of dist. The next chapters use the hello-api:2 image, so build it with this command:

docker build -t hello-api:2 .
Show the hello-api version
# syntax=docker/dockerfile:1
FROM node:24-trixie-slim AS prod-deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

FROM gcr.io/distroless/nodejs24-debian13:nonroot
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
COPY package.json server.js ./
COPY --from=prod-deps /app/node_modules ./node_modules
EXPOSE 3000
CMD ["server.js"]
quick-check

In a multi-stage build, what ends up in the final image?

Base images and users#

Every stage above uses Debian 13 ("trixie"). Why not Alpine for the first two?

Words you need:

  • C library: the low-level code that almost every Linux program, Node included, calls to talk to the system. glibc is the one Debian uses. musl is the smaller one Alpine uses.
  • Native module: an npm package that includes compiled C or C++ code. It is compiled against one C library.
  • CA certificates: the trusted list your app needs for HTTPS calls.
  • busybox: one small program that gives a basic shell and common commands.

A native module installed on Alpine is built for musl, so it can crash at runtime in a Debian image. The stages that install packages must match the final image. node:24-slim is still Debian 12 (bookworm) today. So I write node:24-trixie-slim, which matches debian13 in the distroless name.

Choosing a base image#

Sizes below are the compressed download size for amd64 (the common Intel and AMD server chips), from Docker Hub and gcr.io on 24 October 2026. On disk they are bigger.

Base imageDownload sizeWhat is insideGood for
node:24410 MBfull Debian, compilers, gitbuild stages that compile native modules
node:24-trixie-slim83 MBsmall Debian 13, glibc, npma safe default, build stages
node:24-alpine62 MBAlpine Linux, musl, npmsmall images when all packages are plain JS
gcr.io/distroless/nodejs24-debian1355 MBNode and CA certificates, no shell, no npmthe runtime stage

Most pure JavaScript apps run fine on Alpine. Not sure? Use trixie-slim. Distroless leaves an attacker very few tools, but docker exec -it api sh does not work. For debugging, use its :debug-nonroot tag, which adds a busybox shell.

Measure your own result:

docker images hello-api
docker history hello-api:2

docker history shows the size of each layer. A huge COPY layer usually means a gap in your .dockerignore.

On an arm64 Mac (Apple's ARM chips), on 24 October 2026, the first Alpine hello-api image was 171 MB on disk. hello-api:2 was 164 MB. So for a tiny app, distroless wins on fewer tools, not on size. Size drops when the build stage has heavy tools: a small TypeScript API was 299 MB as one stage, and 164 MB with three stages.

Run as a non-root user#

By default a container runs as root. If someone finds a bug in your app, they get root inside the container.

With distroless, the tag decides the user:

TagRuns as
gcr.io/distroless/nodejs24-debian13 (default, latest)root, user ID 0
gcr.io/distroless/nodejs24-debian13:nonrootnonroot, user ID 65532

The distroless build file (static.bzl) sets these users. So always write :nonroot.

With the official Node images (alpine, slim), add a USER line before CMD. The images already have a user named node (user ID 1000). The files you COPY stay owned by root. That is fine, even good: the app can read them but can't change them.

quick-check

You use FROM gcr.io/distroless/nodejs24-debian13 with no tag. Which user runs your app?

Quick check: spot the problems in this Dockerfile. There are five, plus a bonus.

FROM node:latest
COPY . .
RUN npm install
CMD node server.js
Show answer
  1. node:latest changes when a new Node comes out. Pin it: node:24-alpine.
  2. No WORKDIR, so the files land in / with the system files. Add WORKDIR /app.
  3. COPY . . before installing breaks the cache on every code change.
  4. npm install can change the lock file and installs dev packages. Use npm ci --omit=dev.
  5. CMD node server.js is shell form. node:latest is Debian-based, so /bin/sh becomes PID 1 and Node never gets SIGTERM.

Bonus: it runs as root. Add USER node, or use a distroless :nonroot image.

Docker Compose#

hello-api now needs a database on your laptop.

Words you need:

  • Docker Compose: a tool that starts several containers from one YAML file.
  • Service: one entry under services:. Each one becomes a container.
  • Volume: storage that Docker keeps outside the container, so data survives when the container is deleted.
  • Health check: a command Docker runs again and again to see if the app inside is ready.
  • pg_isready: a small Postgres tool that answers "is the database ready for connections?".

When do you use Compose? For local development and tests, when your app needs other services: a database, a cache, a queue. Every person on the team gets the same setup with one command.

Put a file called compose.yaml next to your Dockerfile. The key lines:

services:
  api:
    # ...
      DATABASE_URL: postgres://app:devpassword@db:5432/app
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:18-alpine
    # ...
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
Show full code: compose.yaml
services:
  api:
    build: .
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DATABASE_URL: postgres://app:devpassword@db:5432/app
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:18-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: devpassword
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  pgdata:

Run it:

docker compose up --build
compose-up
  1. Compose creates a private network and the pgdata volume.
  2. It starts the db container first, because api depends on it.
  3. Docker runs pg_isready every 5 seconds until it passes.
  4. db is healthy, so Compose starts the api container.
  5. api connects to db:5432 by service name.
step 1 / 5
Without condition: service_healthy, api could start before Postgres accepts connections.

One command builds your image, pulls Postgres, and starts the database. Compose waits until the database is ready, then starts the API. Press Ctrl+C to stop. docker compose down removes the containers. docker compose down -v also deletes the database data.

The service name is the host name#

Look at the database address: postgres://app:devpassword@db:5432/app. The host is db, not localhost.

Compose puts all services on one private network. On that network, each service can reach the others by service name. Remember the Ports chapter: inside the api container, localhost means the api container itself. Postgres is not there. It is in the db container.

Open the full compose.yaml above. Only api has a ports: entry, and db has none. So only the api container can reach the database, not your laptop or your network. That is what you want for a database.

To try it, run npm install pg. Then add a route to server.js. pg.Pool keeps a few open database connections and reuses them for each query:

import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

app.get('/db', async (req, res) => {
  const { rows } = await pool.query('SELECT now() AS now');
  res.json(rows[0]);
});

Close the pool when the app stops. Change the SIGTERM handler from the Exec form and PID 1 chapter to this:

process.on('SIGTERM', () => {
  server.close(async () => {
    await pool.end();
    process.exit(0);
  });
});

Run docker compose up --build again. curl http://localhost:3000/db returns the database time, like {"now":"2026-10-24T14:55:04.125Z"}.

A few details that save you time:

  • 127.0.0.1:3000:3000 keeps the port on your laptop only, like in the Ports chapter.
  • CMD-SHELL runs the test through a shell, so you can write it as one normal command line.
  • /var/lib/postgresql for Postgres 18. The official postgres image changed this in version 18. Older guides mount /var/lib/postgresql/data, which is right only for version 17 and below.
  • devpassword is for your laptop only. Real passwords come from your platform's secret store at run time, never from a file in git.
quick-check

In Compose, the api container connects to postgres://app:devpassword@localhost:5432/app. What happens?

Quick check: you run docker compose down -v, then docker compose up. Your test data is gone. Why?

Show answer

-v deletes the volumes, and pgdata held the database files. Plain docker compose down removes the containers but keeps the volume, so the data comes back on the next up.

Scanning and build secrets#

Before hello-api:2 leaves your laptop, check it for known security bugs and leaked tokens.

Words you need:

  • CVE: an ID for a publicly known security bug. It looks like CVE-, then a year and a number.
  • Severity: how bad the bug is: LOW, MEDIUM, HIGH or CRITICAL.
  • Unfixed: a bug with no patched version yet. Updating can't fix it, so --ignore-unfixed hides it.

Run this on the distroless image from the Multi-stage builds chapter:

trivy image --severity CRITICAL,HIGH --ignore-unfixed hello-api:2

Trivy is a free scanner from Aqua Security (brew install trivy on a Mac). It lists known security bugs in the image, in the OS packages and in your npm packages. It prints a table with one row per place it checked, and a count of findings in each.

On 24 October 2026, hello-api:2 had 0 findings. The first Alpine hello-api image had 4 HIGH findings. All 4 were in packages that ship inside npm, which the Node image includes. Distroless has no npm, so those bugs are not there. Run it yourself, because the numbers change as new bugs are published.

Docker Desktop also has a scanner built in, Docker Scout. It needs you to log in with a Docker account first:

docker scout cves --only-severity critical,high --only-fixed hello-api:2

Two rules matter more than the tool:

  1. Scan the image you ship. In a multi-stage build, that is the last stage. The build stage has compilers and dev packages, but they never reach production.
  2. Scan often. An image that was clean last month may not be clean today. Rebuild with docker build --pull to get the newest patched base image.

Secrets in layers#

Your app installs a private npm package. The registry needs a token, which lives in .npmrc. What is wrong with this?

COPY .npmrc ./
RUN npm ci
RUN rm .npmrc
token-in-a-layer
  1. COPY .npmrc saves the token in its own layer.
  2. RUN rm .npmrc only hides the file. ls in the finished image shows no .npmrc.
  3. Anyone who can pull the image can pull the token out of the COPY layer.
step 1 / 3
A deleted file still lives in the earlier layer, as the Layers and the build cache chapter showed.

The Docker docs on build secrets add that build arguments and environment variables "persist in the final image" too.

The fix is a secret mount. The file exists only while that one RUN step runs:

# syntax=docker/dockerfile:1
FROM node:24-trixie-slim AS prod-deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci --omit=dev
docker build --secret id=npmrc,src=$HOME/.npmrc -t hello-api:2 .

id=npmrc links the two. src is the file on your machine. target is where it shows up during that RUN step. npm reads /root/.npmrc because the build runs as root at that point.

How you give the tokenIs it in the image?
COPY .npmrc, then RUN rm .npmrcyes, in the COPY layer
ARG NPM_TOKENyes
ENV NPM_TOKEN=...yes
RUN --mount=type=secret,...no

Runtime secrets (database passwords, API keys) are different. Your platform hands them to the container when it starts, as environment variables or files. ECS and Cloud Run both can do this. They never go in the image.

quick-check

Which way of giving npm a token leaves nothing in the image?

GitHub Actions build and push#

The last step of the story: hello-api reaches a registry on every merge to main, with no known security bugs inside.

Words you need:

  • Workflow: a YAML file in .github/workflows/ that GitHub runs on events like a push.
  • Runner: the fresh virtual machine that runs the job (ubuntu-latest).
  • Gate: a step that stops the job when a check fails.
  • Buildx: Docker's build tool. The setup step starts it, so the build can use the GitHub Actions cache.
  • Labels: small notes stored in the image, like which repo and commit it came from.
  • GITHUB_TOKEN: a short-lived token GitHub creates for each run. With packages: write, it can push to GHCR.

Save the workflow as .github/workflows/docker.yml. The key lines:

on:
  push:
    branches: [main]
  pull_request:
# ...
      # 1. build and load into the runner's Docker, no push yet
      - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          # ...
          load: true
          tags: local/app:scan
# ...
      # 2. the gate: fail the job on fixable CRITICAL or HIGH CVEs
      - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          # ...
          exit-code: '1'

      # 3. push only from main, only after the scan passed
# ...
      - if: github.event_name != 'pull_request'
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          # ...
          push: true
          tags: ${{ steps.meta.outputs.tags }}
Show full code: docker.yml
name: docker

on:
  push:
    branches: [main]
  pull_request:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

      - id: meta
        uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
        with:
          images: ghcr.io/${{ github.repository }}
          tags: |
            type=sha
            type=ref,event=branch

      # 1. build and load into the runner's Docker, no push yet
      - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          load: true
          tags: local/app:scan
          cache-from: type=gha
          cache-to: type=gha,mode=max

      # 2. the gate: fail the job on fixable CRITICAL or HIGH CVEs
      - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          image-ref: local/app:scan
          severity: CRITICAL,HIGH
          ignore-unfixed: true
          exit-code: '1'

      # 3. push only from main, only after the scan passed
      - if: github.event_name != 'pull_request'
        uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - if: github.event_name != 'pull_request'
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha

Open the full file to see the rest. It also has a concurrency block, a Buildx setup step, the build cache lines, and a metadata-action step with id: meta that makes the image tags.

On a pull request it builds and scans, so a bad change fails before you merge. On main it also pushes to GHCR, GitHub's container registry.

The concurrency block groups runs by branch. With cancel-in-progress: true, a new push cancels the older run on the same branch, so you don't wait for outdated builds.

Scan before you push#

Follow a push to main:

build-scan-push
  1. Checkout gets the code, Buildx sets up the builder.
  2. metadata-action works out the tags: sha-860c190 and main.
  3. Build the image and load it into the runner, nothing pushed.
  4. Trivy scans it: a fixable CRITICAL or HIGH CVE fails the job here.
  5. Scan passed, so log in to GHCR.
  6. Build again (all layers come from cache) and push both tags.
step 1 / 6
If the scan fails, the image never reaches the registry, so no server can pull it.

Why scan first? Anything in the registry can be deployed. If the scan runs after the push, the bad image is already there. The second build is fast, because every layer is in the cache from step 3. Docker's own test before push guide uses the same pattern.

cache-to: type=gha,mode=max stores layers in the GitHub Actions cache between runs. mode=max saves the layers of every stage, including build and prod-deps. The default, min, saves only the final image's layers.

Tags: the SHA tag and lowercase names#

Say the repo is MyOrg/Hello-API and the commit is 860c190.... The workflow pushes two tags:

  • ghcr.io/myorg/hello-api:sha-860c190
  • ghcr.io/myorg/hello-api:main

The SHA tag is short. The metadata-action docs say type=sha makes a tag like sha-860c190, with 7 characters by default. A full commit SHA has 40. A tag you write by hand as sha-${{ github.sha }} was never pushed. Use the tags from steps.meta.outputs everywhere.

Image names must be lowercase. github.repository keeps the capitals. metadata-action lowercases the image name for you. A name you build by hand from github.repository fails with repository name must be lowercase.

For deploys, use the sha- tag. It points to one exact build. main moves on every merge.

Pin actions to a commit SHA#

Every uses: line above ends with a 40-character commit SHA and a version comment. Why not write @v0.36.0? Because a tag can be moved.

On 19 March 2026, attackers rewrote most version tags of aquasecurity/trivy-action. The tags pointed at code that stole CI secrets (Snyk's write-up). Workflows that used a tag ran that code. Workflows pinned to a commit SHA did not.

GitHub's security guide recommends pinning to a full commit SHA. Dependabot (GitHub's bot that opens pull requests to update dependencies) still works with pins. It reads the version comment and updates both the SHA and the comment.

In October 2026 GitHub added workflow lockfiles (public preview). They lock every action for you.

The SHAs above match the latest releases on 24 October 2026. Check each action's releases page before you copy the workflow.

quick-check

The workflow pushes with type=sha. Your deploy step uses ghcr.io/myorg/hello-api:sha-${{ github.sha }}. What happens?

quick-check

Why does the scan run before the push step?

Quick check: your repo is MyOrg/Shop-API and you write tags: ghcr.io/${{ github.repository }}:latest by hand. What breaks?

Show answer

The image name becomes ghcr.io/MyOrg/Shop-API, with capitals. The build step fails with invalid tag ... repository name must be lowercase. Let metadata-action make the tags. Also, latest moves on every push, so deploy the sha- tag instead.

Recap#

ProblemWhat you can now do
works on the laptop, crashes on the serverbuild one image and run that same image everywhere
secrets and junk in the imageadd a .dockerignore, use npm ci --omit=dev
the browser can't reach the apppublish with -p 127.0.0.1:..., listen on 0.0.0.0 and the PORT you get
every rebuild reinstalls packagespackage files and npm ci first, COPY . . last
docker stop hangs, exit code 137exec form plus a SIGTERM handler
build tools ship in the imagemulti-stage build, a matching base image, distroless :nonroot
the app needs a databaseCompose, with the service name as the host
known bugs, tokens in layersscan the final stage with Trivy or Docker Scout, use --mount=type=secret
shipping by handbuild, scan, then push from GitHub Actions, with actions pinned to a SHA

Try it yourself:

  • Add a .dockerignore to a project you have. Then run docker history and look for a huge COPY layer.
  • Run docker stop on your container, then read the exit code with docker inspect. 137 means the app had no clean shutdown.
  • Run Trivy on an image you ship today.

Read next: ECS Fargate from Zero deploys this image on AWS. Cloud Run from A to Z deploys it on Google Cloud.