Stage 1 · Foundations · Chapter 5 of 20 · 6 min read

Running containers

The flags on docker run decide how you interact with a container and how it cleans up after itself.

? What do the diagram colours mean

key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral

Three ways to start

Pick the mode by what you want your terminal to do.

Three ways to start a containerDetached keeps your terminal free, interactive attaches your keyboard, and --rm deletes the container on exit.-d detachedYour terminalContainerserver in backgroundterminal stays freeread output: docker logs-it interactiveYour terminalContainershell inside containerkeyboard attachedexit stops it--rm auto-cleanYour terminalContainerone-off jobs, testsstops, then is deletedno dead containers

Configuration at run time

Inject settings with -e so one image serves every environment.

One image, many environmentsThe same image runs as staging and production containers, differing only by the environment variables passed with -e.my-api:1.4one imagestaging containerDATABASE_URL=db-stagingLOG_LEVEL=debugproduction containerDATABASE_URL=db-prodLOG_LEVEL=warn-e ...-e ...
Config changes at run time with -e. The image never changes.

Env files, Dockerfile defaults, ARG versus ENV and secrets are covered in chapter 6.

States and cleanup

Container statesA container goes from created to running to exited. With --rm it is removed automatically when it exits.Createddocker createstartRunningmain process aliveexitExiteddocker ps -armRemovedgone--rm: removed automatically on exit
--rm skips the Exited resting place: the container is removed the moment it stops.

run versus exec

run versus execdocker run creates a new container. docker exec starts an extra process inside a container that is already running.docker run alpine sleep 300creates a NEW containercontainer api (one set of namespaces)PID 1sleep 300PID 7printenv PORTdocker exec api printenvadds a process to apijoins the same container
exec shares the container namespaces, so it sees the same files, environment and network.
FlagUse it for
-dservers: run in the background, read with docker logs name
-ita shell to look around: docker run -it --rm alpine sh
--rmthrowaway containers: migrations, tests, experiments
-e KEY=valueconfiguration that differs per environment
--namea stable name to use with logs, exec and stop

Logs, exec, inspect and stats

When a container misbehaves, four read-only commands answer almost every first question.

Four windows into a running containerdocker logs reads what the main process wrote to stdout and stderr; docker exec starts a new process inside it; docker inspect reads its configuration and state; docker stats reads live CPU and memory use.Container apimain process: node server.jsdocker logs -fstdout / stderrdocker exec -ita 2nd process, a shelldocker inspectconfig, state, exit codedocker statslive CPU, memory, I/ONone of these restart or change the container. They only look.
Logs are only what the main process prints. An app that logs to a file inside the container shows nothing here.
CommandAnswers
docker logs -f --tail 50 apiwhat is it printing right now? -f follows, --tail skips old lines
docker exec -it api shwhat does it see? files, env, DNS, from the inside
docker inspect -f '{{.State.Status}} {{.State.ExitCode}}' apiis it running, and why did it stop?
docker stats --no-streamhow much CPU and memory is each container using?
docker top apiwhich processes run inside it?

Restart policies

A long-running service should come back after a crash or a reboot. That is a flag on docker run, not a script.

Restart policiesWith no policy a crashed container stays stopped. on-failure restarts it after a non-zero exit. always and unless-stopped restart it whenever it stops, and unless-stopped respects a manual docker stop across daemon restarts.Process exitscrash or exit 1Restart policydecides what nextStarted againsame container, same configDocker waits a little longer after each restart (back-off), so a crash loop does not spin the CPU.
PolicyRestarts whenGood for
no (default)neverone-off jobs
on-failure[:5]the process exits non-zero, at most 5 timesworkers that may crash
alwaysit stops for any reason, and when the daemon startsservices that must run
unless-stoppedlike always, but not after you docker stop itmost long-running services

--restart cannot be combined with --rm: one says “keep it”, the other says “delete it”.

Try it yourself

  1. Step 1 · An interactive shell

    -it attaches your keyboard. exit stops the container, and --rm deletes it.

    $ docker run -it --rm --name shell alpine:3.20 sh
    / # ls /
    bin    etc    lib    root   tmp
    / # exit
    $ docker ps -a --filter name=shell
    CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
  2. Step 2 · Detached, named, with an environment variable
    $ docker run -d --name api --rm -e PORT=3000 alpine:3.20 sleep 300
    b22e91aa10c4
    $ docker ps --filter name=api
    CONTAINER ID   IMAGE          STATUS         NAMES
    b22e91aa10c4   alpine:3.20    Up 2 seconds   api
  3. Step 3 · logs and exec use the name

    exec starts a second process in the same container. It can read PORT because -e set it at run.

    $ docker logs api
    $ docker exec api printenv PORT
    3000
  4. Step 4 · stop plus --rm removes the container
    $ docker stop api
    api
    $ docker ps -a --filter name=api
    CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
  5. Step 5 · A restart policy in action

    This container fails on purpose. With on-failure:3 Docker tries three more times, then gives up.

    $ docker run -d --name flaky --restart on-failure:3 alpine:3.20 sh -c 'echo starting; exit 1'
    $ sleep 10
    $ docker inspect -f '{{.RestartCount}} restarts, status={{.State.Status}} exit={{.State.ExitCode}}' flaky
    3 restarts, status=exited exit=1
    $ docker logs flaky
    starting
    starting
    starting
    starting
    $ docker rm flaky
  6. Step 6 · Live resource use
    $ docker run -d --name busy --rm alpine:3.20 sh -c 'while true; do :; done'
    $ docker stats --no-stream busy
    NAME   CPU %    MEM USAGE / LIMIT
    busy   99.8%    412KiB / 7.6GiB
    $ docker stop busy

    The limit column is the whole machine. Chapter 18 shows how to cap it.

Common mistakeAsking why docker logs is empty when the app writes its log to a file inside the container. Docker only captures stdout and stderr. In containers, log to the console.

Recap

Quick check

A container started with -d exits after one second. Where do you look first?

Show answer

Answer: docker ps -a for the exit code, then docker logs.

docker ps -a shows the exit code and docker logs shows what the process printed. A container lives only as long as its main process.

Which restart policy brings a service back after a crash and after a reboot, but leaves it stopped after you run docker stop?

Show answer

Answer: unless-stopped

unless-stopped restarts on crashes and when the daemon starts, unless you stopped the container yourself.