Running containers
The flags on docker run decide how you interact with a container and how it cleans up after itself.
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
Three ways to start
Pick the mode by what you want your terminal to do.
Configuration at run time
Inject settings with -e so one image serves every environment.
States and cleanup
run versus exec
| Flag | Use it for |
|---|---|
-d | servers: run in the background, read with docker logs name |
-it | a shell to look around: docker run -it --rm alpine sh |
--rm | throwaway containers: migrations, tests, experiments |
-e KEY=value | configuration that differs per environment |
--name | a stable name to use with logs, exec and stop |
Try it yourself
-
Step 1 · An interactive shell
-itattaches your keyboard.exitstops the container, and--rmdeletes 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 -
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 -
Step 3 · logs and exec use the name
execstarts a second process in the same container. It can readPORTbecause-eset it atrun.$ docker logs api $ docker exec api printenv PORT 3000 -
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
Recap
-ddetaches,-itattaches your keyboard,--rmdeletes on exit.- Use
-efor config that changes per environment, never rebuild for it. - A container lives while its main process lives. When that exits, so does the container.
docker execadds a process to a running container;runcreates a new one.
Quick check
A container started with
-d exits after one second. Where do you look first?Show answer
docker ps -a to see the exit code, then docker logs name. A container stays up only as long as its main process runs.