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
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 | Container | |
|---|---|---|
| Isolation | Hardware level, strong | Kernel 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
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.
| Thing | Python analogy | Mutable? |
|---|---|---|
| Image | A class | No. A change makes a new image. |
| Container | An instance | Yes, in a thin writable layer that dies with it |
| Registry | PyPI | Tags 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
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.| Command | Effect |
|---|---|
docker run -d --name tut-bank IMAGE | Create and start in the background |
docker ps / docker ps -a | Running containers / all, including exited |
docker stop / docker kill | SIGTERM, then SIGKILL after a grace period / SIGKILL now |
docker rm -f tut-bank | Kill and remove |
Building images
Part 2 of 6 · Dockerfile, layers, cache, size, PID 1
The service
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 to127.0.0.1inside a container is unreachable from outside it. - It handles SIGTERM. PID 1 and signals shows why that matters.
A first Dockerfile
The shortest Dockerfile that works. It has four problems, fixed one by one in the next chapters.
| Problem | Fix |
|---|---|
COPY . . before pip install | Order for cache hits |
COPY . . copies everything | .dockerignore |
| Runs as root | Non-root user |
Shell-form CMD (the warning) | Exec form |
Layers and the build cache
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.
app.py: dashed layers are cached, COPY and pip install run again.Rule: order instructions from least often changed to most often changed. Base image, system packages, dependency manifest, install, source code.
.dockerignore
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
One Dockerfile, several FROM stages. Only the last stage ships, and it copies in just the artefacts it needs from the earlier ones.
- 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
Smaller images pull faster and have fewer packages to patch. The final Dockerfile above already applies most of this table.
| Practice | How | Why |
|---|---|---|
| Slim base | python:3.13-slim, distroless, scratch for Go | Fewer packages, fewer CVEs |
| Non-root user | USER 10001 | A break-in is not root in the container |
| Pinned versions | redis==8.2.0, base tag or digest | Same build tomorrow |
| No package cache | pip install --no-cache-dir | Cache is dead weight in a layer |
| No secrets | Pass at run time | Layers are readable forever |
| Read-only filesystem | docker run --read-only | Attackers 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
ENTRYPOINT is the program, CMD is its default arguments. With no ENTRYPOINT, CMD is the whole command.
| Dockerfile | docker run IMAGE | docker run IMAGE x y |
|---|---|---|
CMD ["python", "app.py"] | python app.py | x y (CMD replaced) |
ENTRYPOINT ["python", "app.py"] | python app.py | python app.py x y |
ENTRYPOINT ["python"] + CMD ["app.py"] | python app.py | python x y |
- The first run replaced
CMDwithid. That is the quickest way to look inside an image. --entrypointoverridesENTRYPOINT, and everything after the image name becomes its arguments.
PID 1 and signals
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.
| PID 1 is | Measured docker stop -t 10 | Exit code |
|---|---|---|
sh -c wrapping the app | 10.2s, killed | 137 |
| The app, with a SIGTERM handler | 0.14s, clean | 0 |
| A Python script with no handler | 10.2s, killed | 137 |
Same script with docker run --init | 0.12s | 143 |
- The kernel ignores SIGTERM for PID 1 unless the process installed a handler: that is row three.
--initputs a tiny init process at PID 1 that forwards signals and reaps zombies. - In a wrapper script, end with
exec python app.pyso 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
A container has its own network namespace, so its port 8000 is invisible to the host until it is published with -p HOST:CONTAINER.
-p 8080:8000alone listens on every host interface. Prefix127.0.0.1:on a laptop.EXPOSEin a Dockerfile publishes nothing. It is documentation.
Configuration and secrets
The image holds code, the environment holds configuration. The same image then runs unchanged in dev, staging and production.
| Where | Use for | Leaks through |
|---|---|---|
ENV, ARG, COPY .env | Never secrets | Image layers and history |
-e, --env-file | Config, dev secrets | docker inspect, child processes |
| Mounted secret file | Production secrets | Only the mounted path |
RUN --mount=type=secret | Secrets needed during build | Nothing: not stored in a layer |
The last two rows were not run for this page.
Volumes, bind mounts, tmpfs
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.
docker rm.| Type | Lives in | Use for |
|---|---|---|
| Named volume | Docker's storage area | Database files, anything stateful |
| Bind mount | A host path you choose | Live source code in dev, config files |
| tmpfs | Memory | Scratch 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
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.
tut-net can reach it.- Inside a container,
localhostis the container itself, not the host and not another container. - Container IPs change on restart. Always connect by name.
logs, exec, inspect
Three commands answer most questions about a running container: what it printed, what is inside it, and how it was configured.
| Command | Answers |
|---|---|
docker logs -f --since 10m NAME | What PID 1 wrote to stdout and stderr |
docker exec -it NAME sh | A shell inside the running container |
docker inspect NAME | Full 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
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.
--restart | Restarts when |
|---|---|
no (default) | Never |
on-failure[:N] | Exit code is not 0, at most N times |
always | Any exit, and when the daemon starts |
unless-stopped | As 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" 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.
--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
HEALTHCHECKand uses its own probes.
Compose
Part 4 of 6 · the API and Redis in one file
compose.yaml
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
docker compose down removes containers and the network but keeps named volumes. The deposit below survives a full down and up.
docker compose down -valso deletes the volumes: the data is gone.
Profiles, overrides, everyday commands
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.
| Command | Does |
|---|---|
docker compose up -d --build | Build, create, start; recreate only what changed |
docker compose ps / logs -f api | Status / follow one service's logs |
docker compose exec api sh | Shell in a running service |
docker compose run --rm SERVICE CMD | One-off container, such as a migration |
docker compose -f compose.yaml up -d | Use only that file: skips the override |
docker compose down / down -v | Remove containers and network / and volumes |
Debugging
Part 5 of 6 · exits, differences between machines, size, errors
A container that exits at once
docker ps shows nothing because the container is no longer running. Look at docker ps -a, the exit code, then the logs.
| Exit code | Meaning | Look at |
|---|---|---|
| 0 | Main process finished normally | Is the command a server, or did it daemonise? |
| 1, 2 | The app failed | docker logs |
| 125 | Docker itself failed to run it | The docker run flags |
| 126 / 127 | Command not executable / not found | CMD, PATH, file permissions |
| 137 | SIGKILL: out of memory or stop timeout | .State.OOMKilled |
| 143 | SIGTERM with no handler | Usually 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"
The image is the same everywhere. What differs is how it was built and what surrounds it at run time.
| Cause | Symptom | Fix |
|---|---|---|
Floating tags (latest, 3.13-slim) | Rebuild picks up a new base | Pin by digest in CI |
| Unpinned dependencies | New library version in the next build | Lock file with exact versions |
| CPU architecture | exec format error on the server | docker build --platform linux/amd64 |
| Dev bind mount hides image files | Works locally, file missing in CI | Test the image with no mounts |
Local .env or override file | Variable unset in production | Fail fast on missing config |
localhost in a URL | Connection refused in the container | Service 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
docker history lists every layer with its size, newest first. The big rows are where to cut.
| Command | Removes |
|---|---|
docker container prune | Stopped containers |
docker image prune / -a | Untagged images / every image no container uses |
docker builder prune | Build cache |
docker volume prune | Unused volumes: this is data |
docker system prune | Stopped 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
Each message below was produced on purpose with the bank image. Long ids are trimmed.
| Message | Cause | Fix |
|---|---|---|
Bind for 127.0.0.1:8080 failed: port is already allocated | Another container publishes that host port | Other host port, or stop the other one |
Conflict. The container name "/tut-bank" is already in use | A stopped container still holds the name | docker rm tut-bank, or --rm |
exec: "pythn": executable file not found in $PATH (exit 127) | Typo in the command, or binary not in the image | Fix CMD; check with --entrypoint sh |
python: can't open file '/app/missing.py' (exit 2) | File not copied, wrong WORKDIR, or ignored | docker 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 registry | Check the tag; log in to the registry |
failed to compute cache key: ... "/nope.txt": not found | COPY source missing from the context or ignored | Check the path and .dockerignore |
touch: cannot touch '/app/x': Permission denied | Non-root user writing to a root-owned path | Write to a volume, or COPY --chown |
Production notes
Part 6 of 6 · tags, a checklist, and the bridge to Kubernetes
Tags versus digests
A tag is a movable pointer. A digest is the SHA-256 of the image content, so it can only ever mean one image.
| Reference | Stable? | Use |
|---|---|---|
tut-bank:latest | No. Whatever was pushed last. | Never deploy it |
tut-bank:1.0.0, tut-bank:<git sha> | By convention only | Release tags: never overwrite them |
tut-bank@sha256:... | Yes | Deploy 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
Most of this is the twelve-factor app applied to containers.
| Rule | In practice | Why |
|---|---|---|
| Config in the environment | One image for every stage, config injected | What was tested is what ships |
| Log to stdout and stderr | No log files in the container, PYTHONUNBUFFERED=1 | The platform collects and rotates |
| One process per container | API, worker and cron are separate containers | Scale, restart and limit each alone |
| Stateless and disposable | State in a database or volume, fast start, clean SIGTERM | Any replica can be killed |
| Scan images | Docker Scout, Trivy or Grype in CI; rebuild on base updates | CVEs arrive after the build |
| Non-root, read-only, limited | USER, --read-only, memory and CPU limits | Smaller blast radius |
| Health endpoint | /health that is cheap and honest | Orchestrators route and restart on it |
No scanner was run for this page.
From Docker to Kubernetes
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.
docker run flags moves into the Pod spec.| Docker | Kubernetes |
|---|---|
ENTRYPOINT / CMD | command / args |
-e, --env-file | env, ConfigMap, Secret |
-p 8080:8000 | containerPort plus a Service |
| Container name as DNS name | Service name as DNS name |
-v name:/data | PersistentVolumeClaim |
--memory, --cpus | resources.requests and limits |
HEALTHCHECK | Ignored: liveness, readiness and startup probes |
--restart | restartPolicy, and a Deployment replaces Pods |
docker stop grace period | terminationGracePeriodSeconds, 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
| Question | Short 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.