Running containers deliberately: ports, volumes, bind mounts, devices and GPUs, environment and logs
Run the notes API image the way you would on a server: publish its port on purpose, pass configuration through the environment, keep data in a volume, read logs, inspect and exec, restrict what it may do, and diagnose a container that crash-loops on a bind mount.
Contentsand lesson path
On this page
- The problem
- Step 1: Publish the port, and choose who can reach it
- Step 2: Configure it with environment variables
- Step 3: Keep data in a named volume
- Step 4: Look inside with logs, exec and inspect
- Step 5: Diagnose a crash loop
- Step 6: Restrict what the container may do
- Exit codes and restart policies
- Devices, GPUs and one-off tools
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Containerization
- A container is a process with boundaries Concept · 15 min
- Images, overlay layers, the build cache and what not to bake in Concept · 20 min
- Lab: from a naive Dockerfile to a slim, non-root multi-stage image Lab · 30 min
- Running containers deliberately: ports, volumes, bind mounts, devices and GPUs, environment and logs Worked example · 25 min
- Lab: an app and its database with Compose, health checks and a live-reload loop Lab · 30 min
- Check: debug three broken containers Knowledge check · 8 questions
What you will learn
- Run and debug containers: publish ports, mount volumes, pass configuration through environment variables, read logs and exec into a running container.
01. The problem
In the lab you built notes-api:slim. A plain docker run notes-api:slim starts it, but nobody can reach it, its notes vanish when the container is replaced, and nothing brings it back if it crashes. This worked example runs the same image deliberately, one flag at a time, on one Linux machine: reachable only locally, configured per environment, keeping its data, restricted and restarted on failure. Along the way you diagnose a colleague's run that keeps restarting.
The outputs come from Docker Engine 29.8 on Linux; container IDs, timings and dates vary. Each step starts by removing the previous container with docker rm -f notes.
02. Step 1: Publish the port, and choose who can reach it
docker run -d --name notes -p 127.0.0.1:8000:8000 notes-api:slim
docker port notes
sleep 2; curl -s localhost:8000/health; echo5fb01243c4e22bcb69ae06ef98c5ed51270c325cae18c36a085df83ddb601907
8000/tcp -> 127.0.0.1:8000
{"status":"ok","env":"dev"}-p takes HOST_IP:HOST_PORT:CONTAINER_PORT. The container has its own network namespace, so its port 8000 is private until you publish it, and uvicorn must listen on 0.0.0.0 inside the container: 127.0.0.1 there is the container's own loopback, which no published port can reach.
Leave out the host IP (-p 8000:8000) and Docker publishes on every interface. On Linux its NAT rules take effect before firewall front ends such as ufw, so a ufw rule denying port 8000 does not protect a published container. Bind to 127.0.0.1 unless you mean to expose the port. EXPOSE only documents a port; -P publishes every exposed port on a random host port.
03. Step 2: Configure it with environment variables
The same image should run in development, staging and production, with settings passed in when the container starts. -e NAME=value sets one variable; --env-file reads a file of them. The file format is stricter than you might expect:
docker rm -f notes
printf '# staging\nAPP_ENV="staging"\nLOG_LEVEL=info # for now\n' > staging.env
docker run --rm --env-file staging.env notes-api:slim printenv APP_ENV LOG_LEVELnotes
"staging"
info # for nowdocker run --env-file keeps quotes and trailing comments as part of the value; only whole-line comments are skipped. (Compose's .env file, in the next lesson, strips both.) Write plain KEY=value lines. Then start the service with a variable and see where Docker records it:
printf 'APP_ENV=staging\nLOG_LEVEL=info\n' > staging.env
docker run -d --name notes -p 127.0.0.1:8000:8000 --env-file staging.env notes-api:slim
docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' notes | head -n 21afcc1583068269a2d59a9189f87e20cb3b7eeb3eae7728b4858aa60d294c6ad
APP_ENV=staging
LOG_LEVEL=infoEvery value is stored in the container's configuration, readable by anyone who can run docker inspect. That is fine for settings, not for passwords and keys: mount those as files (Compose secrets do this under /run/secrets) and have the app read the file.
04. Step 3: Keep data in a named volume
Everything the app writes goes to the container's writable layer, which is deleted with the container. Mount a named volume at /data instead, write a note, replace the container and read the note back:
docker rm -f notes
docker run -d --name notes -p 127.0.0.1:8000:8000 -v notes-data:/data notes-api:slim
sleep 2
curl -s -X POST localhost:8000/notes -H 'Content-Type: application/json' \
-d '{"title": "Survives replacement"}'; echo
docker rm -f notes
docker run -d --name notes -p 127.0.0.1:8000:8000 \
--mount type=volume,src=notes-data,dst=/data notes-api:slim
sleep 2
curl -s localhost:8000/notes; echo
docker volume inspect notes-data --format '{{.Mountpoint}}'notes
065e637befd422ed3dc4ae256f0f351ce1bea899e72cdda63b3b9e8ccf8bd513
{"title":"Survives replacement","body":""}
notes
2ecf7ffe53fdb348bdb39cda98df36a77c5af6a8f612598bc5afaef3aae8e1be
[{"title":"Survives replacement","body":""}]
/var/lib/docker/volumes/notes-data/_dataDocker created the volume on first use and, because it was empty, copied in what the image had at /data, including its owner, so the non-root app user could write to it. The second run uses the longer --mount syntax, which does the same with named fields. There are three kinds of mount:
- a named volume (
-v notes-data:/data): storage managed by Docker, the right default for databases and app data; - a bind mount (
-v "$PWD/data":/dataor--mount type=bind,...): a host folder, ideal for source code in development and for config files, but it brings the host's file ownership with it; - a tmpfs mount (
--tmpfs /tmp): memory only, gone when the container stops.
One trap: if a bind-mount source folder does not exist, -v silently creates it, owned by root, while --mount refuses with an error.
05. Step 4: Look inside with logs, exec and inspect
docker logs --tail 2 notes
docker exec notes sh -c 'id; ls -l /data'
docker inspect notes \
--format '{{.State.Status}} {{.State.Health.Status}} restarts={{.RestartCount}}'INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: 172.17.0.1:39572 - "GET /notes HTTP/1.1" 200 OK
uid=10001(app) gid=10001(app) groups=10001(app)
total 4
-rw-r--r-- 1 app app 43 Oct 19 14:31 notes.jsonl
running starting restarts=0docker logs shows what PID 1 wrote to stdout and stderr; add -f to follow, -t for timestamps and --since 10m to limit the range. The default json-file driver does not rotate, so set --log-opt max-size=10m --log-opt max-file=3 (or the same in the Engine's daemon.json). docker exec runs a new process inside a running container with the same namespaces and user; docker exec -it notes sh opens a shell. Slim images lack ps and curl, so use sh, python -c and /proc. docker inspect prints the whole configuration and state; the health status reads starting until the first probe passes.
06. Step 5: Diagnose a crash loop
A colleague wants to read the notes file from the host, so they replace the volume with a bind mount of a fresh data folder and add a restart policy. Run their command, wait half a minute and look:
docker rm -f notes
mkdir -p data
docker run -d --name notes --restart on-failure:5 -p 127.0.0.1:8000:8000 \
--mount type=bind,src="$PWD/data",dst=/data notes-api:slim
sleep 30
docker ps -a --filter name=notes --format '{{.Names}} {{.Status}}'
docker inspect --format 'exit={{.State.ExitCode}} restarts={{.RestartCount}}' notes
docker logs --tail 4 notesnotes
471226c484cba831d9dbc18542353da9ba3a7a7033051e09470cf6fa22e35742
notes Exited (3) 11 seconds ago
exit=3 restarts=5
^^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: '/data/notes.jsonl'
ERROR: Application startup failed. Exiting.Read the evidence in order. While it looped, docker ps showed Restarting (3) between attempts; now Docker has used the five restarts on-failure:5 allows and given up. Exit code 3 is uvicorn's code for a failed start-up, and the log, which keeps every attempt, names the cause. docker exec needs a running container, so start a one-off container from the same image with the same mount instead:
docker exec notes id
docker run --rm --mount type=bind,src="$PWD/data",dst=/data notes-api:slim \
sh -c 'id; ls -ldn /data'Error response from daemon: container 471226c484cb…22e35742 is not running
uid=10001(app) gid=10001(app) groups=10001(app)
drwxrwxr-x 2 1000 1000 4096 Oct 19 14:31 /dataThe folder belongs to UID 1000, the colleague's host user, and only its owner and group may write. The container runs as UID 10001, which counts as "other": a bind mount shows the host's numeric ownership as it is. Three fixes work:
- run the container as the host user:
--user "$(id -u):$(id -g)"; - give the folder to the container's user:
sudo chown 10001:10001 data; - or go back to a named volume, unless someone really needs the file on the host.
Apply the first and check that it stays up:
docker rm -f notes
docker run -d --name notes --restart on-failure:5 --user "$(id -u):$(id -g)" \
-p 127.0.0.1:8000:8000 --mount type=bind,src="$PWD/data",dst=/data notes-api:slim
sleep 12
docker ps --filter name=notes --format '{{.Names}} {{.Status}}'notes
eababa1872dc255b55ba20472a9c1b69040b02d62f79c0642b5288c5a95d7f10
notes Up 12 seconds (healthy)On Docker Desktop for macOS and Windows, bind mounts pass through the VM's file sharing, which maps ownership, so this exact error rarely appears there. On Linux servers and in CI it is one of the most common reasons a non-root image fails.
07. Step 6: Restrict what the container may do
The app needs to write to /data and nothing else. Make everything else read-only, give it a scratch /tmp in memory, drop every Linux capability, forbid privilege escalation, cap its memory and CPU (the limits from lesson 1), restart it unless you stop it yourself, and rotate its logs:
docker rm -f notes
docker run -d --name notes -p 127.0.0.1:8000:8000 -v notes-data:/data \
--read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
--memory 256m --cpus 1 --restart unless-stopped \
--log-opt max-size=10m --log-opt max-file=3 notes-api:slim
sleep 12
docker ps --filter name=notes --format '{{.Names}} {{.Status}}'
docker exec notes sh -c 'touch /app/x; grep -E "CapEff|CapBnd" /proc/1/status'notes
f0bcba8d4a221092d8f10264ce4bfdd64e31d58a059033d2bd7b7275a85ea389
notes Up 12 seconds (healthy)
touch: cannot touch '/app/x': Read-only file system
CapEff: 0000000000000000
CapBnd: 0000000000000000Read the two capability lines with care. CapEff lists the capabilities in use now, and a non-root process such as app has none even without --cap-drop. The line that proves the flag worked is CapBnd, the bounding set: the most the process could ever gain. --cap-drop ALL empties it; without the flag it reads 00000000a80425fb, Docker's default set. The service is healthy with no capabilities, and a compromised process running as app could not change its code, barring a kernel or runtime exploit. If an app fails under --read-only, its error names the path; add a --tmpfs or volume for that path.
08. Exit codes and restart policies
The exit code is often the fastest clue; above 128 it means killed by signal (code minus 128):
- 0: the process ended normally.
- 1 or another small number: the application reported an error; read the logs (uvicorn uses 3 for a failed start-up).
- 125:
docker runitself failed, for example an invalid flag value. - 126: the command exists but cannot be executed (permissions, wrong format).
- 127: the command was not found in the image's
PATH, often a typo inCMD. - 137:
SIGKILL: the memory limit (checkOOMKilled) or adocker stopthat ran out of patience. - 143:
SIGTERMended a process that did not handle it.
Restart policies decide what Docker does when the process exits: no (the default), on-failure[:N] (only after a non-zero exit, at most N times), always, and unless-stopped (like always, but a container you stopped stays stopped after the daemon restarts). Docker waits 100 ms before the first restart and doubles the delay each time, resetting it once a container has run for 10 seconds. A failing health check does not trigger a restart on its own: plain Docker only reports unhealthy.
09. Devices, GPUs and one-off tools
--device /dev/ttyUSB0 gives a container one host device without the blanket access of --privileged. GPUs need the NVIDIA driver on the host plus the NVIDIA Container Toolkit, which injects the driver into the container; the image carries only CUDA user-space libraries (for example from an nvidia/cuda base image), in a version the host driver supports:
docker run --rm --gpus all nvidia/cuda:13.4.3-base-ubuntu24.04 nvidia-smiIt prints the nvidia-smi table of GPUs. We could not run it: our machine has no GPU, and there Engine 29 refuses --gpus all with exit code 125 and "failed to discover GPU vendor from CDI: no known GPU vendor found". Compose expresses the same request under deploy.resources.reservations.devices.
Containers also run a tool once without installing it; -i passes your input in:
curl -s localhost:8000/notes | docker run --rm -i python:3.12-slim python -m json.tool
docker rm -f notes && docker volume rm notes-data[
{
"title": "Survives replacement",
"body": ""
}
]
notes
notes-data10. Common mistakes
11. Check your understanding
12. Apply it
Write a run-local.sh for your practice project that starts its image the way this lesson ended, with the limits you measured in lesson 1 and only the writable paths it needs. Then break it three ways (a missing setting, a bind mount with the wrong owner, a typo in the command) and record for each the exit code, the log line that names the cause and the command that confirmed it.
13. Review prompt
Without looking back, write the docker run command for this service with every flag from step 6, and explain each flag in a few words. Then answer: why can docker exec not help with a crash loop, and what do you do instead? What do exit codes 3, 125, 127 and 137 tell you? What is the difference between a named volume, a bind mount and a tmpfs mount, and which one would you use for a Postgres data directory?
References
- Docker Docs: Port publishing and mapping
- Docker Docs: Packet filtering and firewalls
- Docker Docs: Volumes
- Docker Docs: Bind mounts
- Docker Docs: tmpfs mounts
- Docker Docs: docker container run
- Docker Docs: Configure logging drivers
- Docker Docs: Start containers automatically
- Docker Docs: GPU access
- NVIDIA Container Toolkit: installation guide
- Docker Docs: Building best practices
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.