Learnings

Cloud and DevOps

Docker for Backend Engineers

How to package a small Python service into an image, run it, wire it to Redis with Compose, debug it and get it ready for production, told mostly in diagrams. Every command was run with Docker 29.0.1 and Compose 2.40.3 on an Apple Silicon Mac, and the output is pasted from those runs.

Why containers

Part 1 of 6 · what a container is, and the three nouns

Container versus virtual machine

Why containers

A virtual machine carries its own operating system kernel. A container is an ordinary Linux process that shares the host kernel and is isolated by namespaces (what it can see) and cgroups (what it can use).

Virtual machine: a whole guest OS per app. Gigabytes, boots in tens of seconds.
Container: one isolated process. Megabytes, starts in well under a second.
Virtual machineContainer
IsolationHardware level, strongKernel level, weaker: a kernel bug is shared

Trap: on macOS and Windows, Docker Desktop runs one hidden Linux VM and every container lives inside it. docker info on this Mac reports linux/aarch64.

Image, container, registry

Why containers

An image is a read-only filesystem plus start-up metadata. A container is a running instance of it, and a registry is where images are stored and shared.

Build once, push, pull anywhere, run as many containers as needed.
ThingPython analogyMutable?
ImageA classNo. A change makes a new image.
ContainerAn instanceYes, in a thin writable layer that dies with it
RegistryPyPITags can move, digests cannot

An image name reads registry/repository:tag. With no registry it means Docker Hub, and with no tag it means latest.

The lifecycle of a container

Why containers

A container lives exactly as long as its main process (PID 1). When that process exits, the container stops, and it stays on disk until it is removed.

docker run is create plus start. docker run --rm adds rm on exit.
CommandEffect
docker run -d --name tut-bank IMAGECreate and start in the background
docker ps / docker ps -aRunning containers / all, including exited
docker stop / docker killSIGTERM, then SIGKILL after a grace period / SIGKILL now
docker rm -f tut-bankKill and remove

Building images

Part 2 of 6 · Dockerfile, layers, cache, size, PID 1

The service

Building images

One file: a tiny bank API on the standard library's http.server. Balances are whole rupees, kept in memory, or in Redis when REDIS_URL is set.

  • It binds 0.0.0.0. A server bound to 127.0.0.1 inside a container is unreachable from outside it.
  • It handles SIGTERM. PID 1 and signals shows why that matters.

A first Dockerfile

Building images

The shortest Dockerfile that works. It has four problems, fixed one by one in the next chapters.

ProblemFix
COPY . . before pip installOrder for cache hits
COPY . . copies everything.dockerignore
Runs as rootNon-root user
Shell-form CMD (the warning)Exec form

Layers and the build cache

Building images

Each instruction makes a layer, and a layer is reused only if it and every layer above it in the file are unchanged. One changed file in a COPY rebuilds that layer and everything after it.

Naive order, after editing app.py: dashed layers are cached, COPY and pip install run again.
Dependencies first: the same edit rebuilds only the last, tiny layer.

Rule: order instructions from least often changed to most often changed. Base image, system packages, dependency manifest, install, source code.

.dockerignore

Building images

The whole build folder (the context) is sent to the builder, and COPY . . puts all of it in the image. Here the folder also held a .venv and a .env with a fake key.

Trap: a .env copied into an image is readable by everyone who can pull it. The image also shrank from 239MB to 224MB.

Multi-stage builds

Building images

One Dockerfile, several FROM stages. Only the last stage ships, and it copies in just the artefacts it needs from the earlier ones.

Build tools stay in the build stage. The runtime stage gets installed packages only.
  • 13MB saved here with one pure-Python dependency. The gain is far larger when the build needs compilers, headers or a whole toolchain.

Small and secure images

Building images

Smaller images pull faster and have fewer packages to patch. The final Dockerfile above already applies most of this table.

PracticeHowWhy
Slim basepython:3.13-slim, distroless, scratch for GoFewer packages, fewer CVEs
Non-root userUSER 10001A break-in is not root in the container
Pinned versionsredis==8.2.0, base tag or digestSame build tomorrow
No package cachepip install --no-cache-dirCache is dead weight in a layer
No secretsPass at run timeLayers are readable forever
Read-only filesystemdocker run --read-onlyAttackers cannot drop files

Trap: deleting a file in a later layer does not shrink the image or hide the file. The earlier layer still holds it.

CMD versus ENTRYPOINT

Building images

ENTRYPOINT is the program, CMD is its default arguments. With no ENTRYPOINT, CMD is the whole command.

Dockerfiledocker run IMAGEdocker run IMAGE x y
CMD ["python", "app.py"]python app.pyx y (CMD replaced)
ENTRYPOINT ["python", "app.py"]python app.pypython app.py x y
ENTRYPOINT ["python"] + CMD ["app.py"]python app.pypython x y
  • The first run replaced CMD with id. That is the quickest way to look inside an image.
  • --entrypoint overrides ENTRYPOINT, and everything after the image name becomes its arguments.

PID 1 and signals

Building images

docker stop sends SIGTERM to PID 1 only, waits for a grace period, then sends SIGKILL. Shell form (CMD python app.py) makes /bin/sh -c PID 1, and that shell does not pass the signal on.

Shell form: the app never hears SIGTERM, so it is killed mid-request.
PID 1 isMeasured docker stop -t 10Exit code
sh -c wrapping the app10.2s, killed137
The app, with a SIGTERM handler0.14s, clean0
A Python script with no handler10.2s, killed137
Same script with docker run --init0.12s143
  • The kernel ignores SIGTERM for PID 1 unless the process installed a handler: that is row three. --init puts a tiny init process at PID 1 that forwards signals and reaps zombies.
  • In a wrapper script, end with exec python app.py so the app replaces the shell.
  • The documented default grace period is 10 seconds. This Docker Desktop used 1 second, so the runs pass -t 10.

Running containers

Part 3 of 6 · ports, config, storage, networks, limits, health

Ports

Running containers

A container has its own network namespace, so its port 8000 is invisible to the host until it is published with -p HOST:CONTAINER.

Left of the colon is the host, right is the container.
  • -p 8080:8000 alone listens on every host interface. Prefix 127.0.0.1: on a laptop.
  • EXPOSE in a Dockerfile publishes nothing. It is documentation.

Configuration and secrets

Running containers

The image holds code, the environment holds configuration. The same image then runs unchanged in dev, staging and production.

WhereUse forLeaks through
ENV, ARG, COPY .envNever secretsImage layers and history
-e, --env-fileConfig, dev secretsdocker inspect, child processes
Mounted secret fileProduction secretsOnly the mounted path
RUN --mount=type=secretSecrets needed during buildNothing: not stored in a layer

The last two rows were not run for this page.

Volumes, bind mounts, tmpfs

Running containers

Anything written inside a container goes to its writable layer and is deleted with the container. Data that must outlive it goes on a mount.

Four places a write can land. Only the volume and the host folder survive docker rm.
TypeLives inUse for
Named volumeDocker's storage areaDatabase files, anything stateful
Bind mountA host path you chooseLive source code in dev, config files
tmpfsMemoryScratch files, secrets that must not hit disk

Trap: a bind mount hides whatever the image had at that path, and it ties the container to one host's layout.

Networks and name-based discovery

Running containers

Containers on the same user-defined network find each other by container name through Docker's built-in DNS. The default bridge network has no such DNS.

Redis publishes no port. Only containers on tut-net can reach it.
  • Inside a container, localhost is the container itself, not the host and not another container.
  • Container IPs change on restart. Always connect by name.

logs, exec, inspect

Running containers

Three commands answer most questions about a running container: what it printed, what is inside it, and how it was configured.

CommandAnswers
docker logs -f --since 10m NAMEWhat PID 1 wrote to stdout and stderr
docker exec -it NAME shA shell inside the running container
docker inspect NAMEFull JSON: mounts, env, network, state, exit code

Trap: docker logs shows only stdout and stderr. An app that logs to a file inside the container shows nothing here.

Resource limits and restart policies

Running containers

Without limits one container can use all of the host's memory and CPU. Limits are cgroup settings, and going over the memory limit gets the process killed.

--restartRestarts when
no (default)Never
on-failure[:N]Exit code is not 0, at most N times
alwaysAny exit, and when the daemon starts
unless-stoppedAs always, but not after a manual stop

Interview point: exit 137 is SIGKILL (128 + 9). Check OOMKilled to tell an out-of-memory kill from a stop timeout.

Health checks

Running containers

"Running" only means PID 1 exists. A HEALTHCHECK is a command Docker runs inside the container on a timer, and its exit code sets the health status.

Three failures in a row (--retries=3) flip the status. One pass flips it back.
  • Plain Docker only labels an unhealthy container. It does not restart it.
  • Compose uses the status for start-up ordering. Kubernetes ignores HEALTHCHECK and uses its own probes.

Compose

Part 4 of 6 · the API and Redis in one file

compose.yaml

Compose

Compose turns the docker run flags from Part 3 into one declarative file. It creates a network for the project, and each service name becomes a DNS name on it.

depends_on with service_healthy: the API starts only after Redis answers.

Trap: plain depends_on: [redis] waits for the container to start, not for Redis to be ready. This app connects at start-up, so it would crash.

Up, down and the named volume

Compose

docker compose down removes containers and the network but keeps named volumes. The deposit below survives a full down and up.

  • docker compose down -v also deletes the volumes: the data is gone.

Profiles, overrides, everyday commands

Compose

A service with a profiles entry starts only when asked for. A compose.override.yaml next to the main file is merged in automatically, which suits dev-only settings.

CommandDoes
docker compose up -d --buildBuild, create, start; recreate only what changed
docker compose ps / logs -f apiStatus / follow one service's logs
docker compose exec api shShell in a running service
docker compose run --rm SERVICE CMDOne-off container, such as a migration
docker compose -f compose.yaml up -dUse only that file: skips the override
docker compose down / down -vRemove containers and network / and volumes

Debugging

Part 5 of 6 · exits, differences between machines, size, errors

A container that exits at once

Debugging

docker ps shows nothing because the container is no longer running. Look at docker ps -a, the exit code, then the logs.

Exit codeMeaningLook at
0Main process finished normallyIs the command a server, or did it daemonise?
1, 2The app faileddocker logs
125Docker itself failed to run itThe docker run flags
126 / 127Command not executable / not foundCMD, PATH, file permissions
137SIGKILL: out of memory or stop timeout.State.OOMKilled
143SIGTERM with no handlerUsually a normal stop

If the logs are empty, start the same image with a shell and run the command by hand: docker run --rm -it --entrypoint sh IMAGE.

"Works on my machine"

Debugging

The image is the same everywhere. What differs is how it was built and what surrounds it at run time.

CauseSymptomFix
Floating tags (latest, 3.13-slim)Rebuild picks up a new basePin by digest in CI
Unpinned dependenciesNew library version in the next buildLock file with exact versions
CPU architectureexec format error on the serverdocker build --platform linux/amd64
Dev bind mount hides image filesWorks locally, file missing in CITest the image with no mounts
Local .env or override fileVariable unset in productionFail fast on missing config
localhost in a URLConnection refused in the containerService names, host.docker.internal for the host

Here: docker image inspect reports the image built on this Mac as arm64/linux. An amd64 server cannot run it unless it is built for that platform (cross-build not run for this page).

Image size and disk space

Debugging

docker history lists every layer with its size, newest first. The big rows are where to cut.

CommandRemoves
docker container pruneStopped containers
docker image prune / -aUntagged images / every image no container uses
docker builder pruneBuild cache
docker volume pruneUnused volumes: this is data
docker system pruneStopped containers, unused networks, dangling images, build cache

The prune commands were not run for this page, because they act on the whole machine. Our own code and dependencies are 7.4MB of the 211MB, so the base image is the lever.

Common error messages

Debugging

Each message below was produced on purpose with the bank image. Long ids are trimmed.

MessageCauseFix
Bind for 127.0.0.1:8080 failed: port is already allocatedAnother container publishes that host portOther host port, or stop the other one
Conflict. The container name "/tut-bank" is already in useA stopped container still holds the namedocker rm tut-bank, or --rm
exec: "pythn": executable file not found in $PATH (exit 127)Typo in the command, or binary not in the imageFix CMD; check with --entrypoint sh
python: can't open file '/app/missing.py' (exit 2)File not copied, wrong WORKDIR, or ignoreddocker run --rm IMAGE ls -A
pull access denied for tut-bank, repository does not exist or may require 'docker login'Tag not found locally, so Docker tried a registryCheck the tag; log in to the registry
failed to compute cache key: ... "/nope.txt": not foundCOPY source missing from the context or ignoredCheck the path and .dockerignore
touch: cannot touch '/app/x': Permission deniedNon-root user writing to a root-owned pathWrite to a volume, or COPY --chown

Production notes

Part 6 of 6 · tags, a checklist, and the bridge to Kubernetes

Tags versus digests

Production notes

A tag is a movable pointer. A digest is the SHA-256 of the image content, so it can only ever mean one image.

ReferenceStable?Use
tut-bank:latestNo. Whatever was pushed last.Never deploy it
tut-bank:1.0.0, tut-bank:<git sha>By convention onlyRelease tags: never overwrite them
tut-bank@sha256:...YesDeploy manifests, base images in CI

Interview point: tag every build with the git commit, deploy by digest, and a rollback is just the previous digest.

Production checklist

Production notes

Most of this is the twelve-factor app applied to containers.

RuleIn practiceWhy
Config in the environmentOne image for every stage, config injectedWhat was tested is what ships
Log to stdout and stderrNo log files in the container, PYTHONUNBUFFERED=1The platform collects and rotates
One process per containerAPI, worker and cron are separate containersScale, restart and limit each alone
Stateless and disposableState in a database or volume, fast start, clean SIGTERMAny replica can be killed
Scan imagesDocker Scout, Trivy or Grype in CI; rebuild on base updatesCVEs arrive after the build
Non-root, read-only, limitedUSER, --read-only, memory and CPU limitsSmaller blast radius
Health endpoint/health that is cheap and honestOrchestrators route and restart on it

No scanner was run for this page.

From Docker to Kubernetes

Production notes

Kubernetes runs the same image. It does not use Docker to do so: the kubelet asks a container runtime such as containerd to pull and start it.

The image is the contract. Everything from the docker run flags moves into the Pod spec.
DockerKubernetes
ENTRYPOINT / CMDcommand / args
-e, --env-fileenv, ConfigMap, Secret
-p 8080:8000containerPort plus a Service
Container name as DNS nameService name as DNS name
-v name:/dataPersistentVolumeClaim
--memory, --cpusresources.requests and limits
HEALTHCHECKIgnored: liveness, readiness and startup probes
--restartrestartPolicy, and a Deployment replaces Pods
docker stop grace periodterminationGracePeriodSeconds, 30 by default

Carry over: exec-form CMD, a SIGTERM handler, a numeric USER and config from the environment all matter more on Kubernetes, not less. No cluster was available, so nothing here was run.

Cheat sheet

Production notes

QuestionShort answer
Why is my build slow?A COPY of changing files sits above the install step
Why is my image big?docker history; slim base, multi-stage, .dockerignore
Why does docker stop hang?PID 1 is a shell or ignores SIGTERM: exec form, handler, --init
Where did my data go?It was in the writable layer. Use a named volume.
How do containers find each other?By name, on a user-defined network or in one Compose project
Why can I not reach the port?Not published with -p, or the app binds 127.0.0.1
Where do secrets go?Injected at run time, never in ENV, ARG or a copied file
Exit 137?SIGKILL: check OOMKilled, then the stop timeout
Start order in Compose?depends_on with condition: service_healthy
What do I deploy?A digest, built once, configured by the environment

Back to Cloud and DevOps.