Skip to the content

Lesson 249 of 296

Docker: images, containers and layers

What you will learn

  • What containers are and the problem they solve
  • Containers vs virtual machines
  • Images, containers, registries
  • Writing a Dockerfile
  • Layers and build caching
  • Essential Docker commands
  • Container best practices
On this page

The problem

"It works on my machine." Your app depends on a Node.js version, system libraries, environment settings. Servers differ. Containers package the app with everything it needs into one unit that runs the same way on a laptop, in CI and in production.

Containers vs virtual machines

Virtual machineContainer
ContainsA full operating system with its own kernelJust the app and its libraries; shares the host's Linux kernel
SizeGigabytesMegabytes
Start timeMinutesSeconds or less
IsolationStrong (hardware virtualisation)Process-level (Linux namespaces and cgroups); slightly weaker
DensityFew per hostMany per host

Key terms

TermMeaning
ImageA read-only template: filesystem + metadata (command, ports, environment). Built from a Dockerfile
ContainerA running instance of an image, with its own writable layer. Many containers can run from one image
RegistryStores and shares images: Docker Hub, AWS ECR, GitHub Container Registry
TagA version label: jobprep-api:1.4.2, node:24-alpine
VolumePersistent storage that outlives containers (databases)

Containers are ephemeral: anything written inside a container's filesystem is lost when it is removed. Data belongs in volumes, databases or object storage.

A Dockerfile

A Dockerfile is the recipe for an image. A simple one for a Node.js API:

FROM node:24-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]
InstructionDoes
FROMThe base image to start from
WORKDIRSets the working directory (creates it)
COPYCopies files from your project into the image
RUNRuns a command at build time (install dependencies)
ENVSets an environment variable
EXPOSEDocuments the port the app listens on (does not publish it)
USERRuns as a non-root user (the official Node image includes a node user)
CMDThe default command when the container starts

CMD ["node", "server.js"] (exec form) vs CMD node server.js (shell form): with the exec form, Node is process 1 and receives SIGTERM directly, so graceful shutdown works (Lesson 193). The shell form wraps it in /bin/sh, which may not pass signals on. Avoid npm start as the command for the same reason.

Layers and caching

Each instruction creates a layer. Docker caches layers and reuses them when nothing they depend on has changed. A changed layer invalidates every layer after it.

That is why the Dockerfile copies package.json and runs npm ci before copying the source code: when you change only source files, the dependency layer is reused from cache and the build takes seconds. If you COPY . . first, every code change re-installs all dependencies.

.dockerignore keeps files out of the build context (faster builds, no secrets in images):

node_modules
.git
.env
dist
coverage
*.log

Essential commands

CommandDoes
docker build -t jobprep-api:1.0 .Build an image from the Dockerfile in the current folder
docker run -d -p 8080:3000 --name api --env-file .env jobprep-api:1.0Run detached, map host port 8080 to container port 3000
docker ps, docker ps -aRunning / all containers
docker logs -f apiFollow a container's output
docker exec -it api shOpen a shell inside a running container
docker stop apiSend SIGTERM, then SIGKILL after 10 seconds
docker rm api, docker rmi imageRemove a container / an image
docker images, docker history imageList images / show an image's layers and sizes
docker push registry/name:tagUpload to a registry

Best practices

  • Small, trusted base images: official images, -alpine or -slim variants, or distroless images; pin versions (node:24-alpine, ideally a digest).
  • Non-root user.
  • One process per container; scale by running more containers.
  • Configuration through environment variables, never baked in; no secrets in images (anyone with the image can read every layer, even if a later layer deletes the file).
  • Log to stdout and stderr; the platform collects logs.
  • Health checks and graceful shutdown on SIGTERM.
  • Scan images for vulnerabilities (Docker Scout, Trivy, ECR scanning).
  • Multi-stage builds to keep production images small (Lesson 250).

How to say it in an interview

"A container packages an app with its dependencies and runs as an isolated process sharing the host kernel, so it is far lighter than a virtual machine. An image is the read-only template built from a Dockerfile, a container is a running instance, and registries like ECR store images. Each Dockerfile instruction is a cached layer, so I copy package files and install dependencies before copying source code. I use small pinned base images, a non-root user, exec-form CMD so the app receives SIGTERM, a .dockerignore, environment variables instead of baked-in config, no secrets in layers, logs to stdout, and vulnerability scanning."

Key words

WordMeaning
ContainerAn isolated running process with its own filesystem
ImageA read-only template for containers
DockerfileThe recipe for building an image
LayerA cached filesystem change from one instruction
RegistryA store of images
Base imageThe image a Dockerfile starts from
VolumePersistent storage for containers
Exec formCMD ["node", "server.js"], which passes signals correctly

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.