Lesson 07 intermediate

Docker Containers

Run containers with the flags that matter, read logs, get a shell inside, set restart policies and resource limits, and stop them the right way.

Most of your time with Docker is spent running and debugging containers. This lesson covers the docker run flags you will use every day, how to see what a container is doing, and how to keep it healthy and well-behaved.

The docker run flags that matter

$ docker run -d --name api \
  -p 8000:8000 \
  -e LOG_LEVEL=info \
  --env-file .env \
  --restart unless-stopped \
  ghcr.io/jeff/api:1.4.2
FlagWhat it does
-dDetached: run in the background and print the container ID
--name apiA fixed name instead of a random one like quirky_turing
-p 8000:8000Publish a port as host:container
-e KEY=value / --env-fileSet environment variables, one by one or from a file
--restart unless-stoppedRestart on crashes and after reboots, unless you stopped it
--rmDelete the container when it exits
-itInteractive terminal, for shells and tools you type into

Tip: -p 127.0.0.1:8000:8000 publishes the port only on localhost. Use it for admin tools and databases that should not be reachable from the internet.

See what is running

$ docker ps
CONTAINER ID   IMAGE                    STATUS                  PORTS                    NAMES
9c1e4b7a2f3d   ghcr.io/jeff/api:1.4.2   Up 2 minutes            0.0.0.0:8000->8000/tcp   api
$ docker ps -a --filter status=exited
CONTAINER ID   IMAGE         STATUS                      NAMES
3a7f2c9e1b4d   worker:2.3    Exited (137) 1 hour ago     worker

The exit code tells a story: 0 is a clean exit, 1 is an application error, and 137 means the process was killed (128 + 9, SIGKILL), often by the out-of-memory killer.

Logs

Containers should log to standard output and standard error. Docker captures both:

$ docker logs --tail 3 api
INFO  Starting api 1.4.2
INFO  Connected to database
INFO  Listening on 0.0.0.0:8000
$ docker logs -f --since 10m api

-f follows new lines like tail -f; press Ctrl+C to stop following without stopping the container.

Get a shell inside

docker exec runs an extra process in a running container. It is the fastest way to check files, environment variables or connectivity from the container’s point of view:

$ docker exec -it api sh
/app # env | grep LOG_LEVEL
LOG_LEVEL=info
/app # wget -qO- localhost:8000/health
{"status":"ok"}
/app # exit

Changes you make this way are lost when the container is recreated. Fix the image, not the container.

Inspect and monitor

$ docker inspect --format '{{.State.Status}} {{.RestartCount}} {{.NetworkSettings.Networks}}' api
running 0 map[bridge:0xc000488000]
$ docker stats --no-stream
CONTAINER ID   NAME   CPU %     MEM USAGE / LIMIT   MEM %     NET I/O          PIDS
9c1e4b7a2f3d   api    0.42%     84.2MiB / 512MiB    16.45%    1.2MB / 860kB    11

Limit resources

Without limits, one container can use all the host’s memory and CPU. Set them explicitly:

$ docker run -d --name worker --memory=512m --memory-swap=512m --cpus=1.5 --pids-limit=200 worker:2.3
$ docker update --memory=768m --memory-swap=768m worker
worker

When a container goes over its memory limit, the kernel kills it, you see exit code 137, and docker inspect --format '{{.State.OOMKilled}}' worker prints true.

Stop containers gracefully

docker stop sends SIGTERM, waits (10 seconds by default), then sends SIGKILL. Applications should catch SIGTERM, finish in-flight requests and exit:

$ docker stop --time 30 api
api
$ docker kill api

docker kill skips the grace period. If your containers always take exactly 10 seconds to stop, the app is ignoring SIGTERM, often because a shell script started it without exec (lesson 8 explains the exec form of CMD).

Clean up

$ docker rm worker
worker
$ docker container prune
Deleted Containers:
3a7f2c9e1b4d
Total reclaimed space: 8.1MB

Exercise

docker stop always takes exactly 10 seconds before your container exits. Why?

  1. The image is too large to stop quickly
  2. The main process ignores SIGTERM, so Docker waits 10 seconds and then sends SIGKILL
  3. Docker waits for the network to detach
  4. Logs are flushed to disk for 10 seconds
Show answer

Answer: B. docker stop sends SIGTERM and waits for the grace period (10 seconds by default) before killing. A shell wrapper as PID 1 often swallows the signal: use the exec form of CMD or handle SIGTERM in the app.

Key takeaways

  • Name your containers, pin image tags and choose a restart policy.
  • docker logs, docker exec and docker stats answer most “what is it doing?” questions.
  • Set memory and CPU limits so one container cannot take down the host.
  • Handle SIGTERM in your app so docker stop can shut it down cleanly.

FAQ

What is the difference between docker run and docker start?

docker run creates a new container from an image and starts it. docker start starts an existing, stopped container again with the settings it was created with.

How do I change a port or environment variable of an existing container?

You cannot change them in place. Remove the container and run it again with the new flags; with Compose, edit the file and run docker compose up -d.

Why can’t I reach my app on the published port?

The most common cause is the app listening on 127.0.0.1 inside the container. Make it listen on 0.0.0.0, then check docker ps to confirm the port mapping.

↑ ↓ navigate Enter open Esc close