docker run is the command you'll use most, and its flags decide how the container behaves.
docker run [options] IMAGE [COMMAND] [ARGS] creates a new container from an image and starts it. The most important options:
-d(detached): run in the background and print the container ID. Without it, the container is attached to your terminal and Ctrl+C stops it.--name api: give it a memorable name instead of a random one likequirky_turing. Names must be unique.-it:-ikeeps stdin open and-tallocates a terminal. Use both for interactive shells:docker run -it ubuntu bash.--rm: delete the container automatically when it exits. Great for one-off commands.-e KEY=value: set an environment variable.-ppublishes ports and-vmounts storage; both are covered later.
Anything after the image name replaces the image's default command (its CMD). docker run python:3.13 python -c "print(42)" runs that instead of the default REPL.
The rule that surprises everyone: a container lives exactly as long as its main process. The command you run is PID 1 inside the container; when it exits, the container stops. That's why docker run -d ubuntu exits immediately: the default command is bash, which ends at once with no terminal attached. A container is not a server you keep booted; it is one process.
Every docker run makes a new container. To restart an existing stopped one, use docker start. Using --rm for experiments keeps old containers from piling up.
Example
docker run --rm alpine echo "hello" # hello (container removed after)
docker run -it --rm ubuntu:24.04 bash # interactive shell; exit to leave
docker run -d --name cache redis:7 # background service
docker run --rm -e NAME=Ada python:3.13 \
python -c "import os; print('hi', os.environ['NAME'])" # hi Ada
docker run -d ubuntu:24.04 # exits at once: bash has no tty
docker ps -a --format '{{.Image}} {{.Status}}'
# ubuntu:24.04 Exited (0) 2 seconds ago
# redis:7 Up 10 secondsRemember
- -d background, --name, -it interactive, --rm auto-cleanup
- Arguments after the image replace its default CMD
- The container stops when its main process (PID 1) exits
- docker run always creates a new container; docker start reuses one
Watch out for
- Putting options after the image name — docker run alpine --rm passes --rm to the container's command, not to Docker.