Docker Tutorial · Docker Basics · Lesson 2 of 26

Running Containers

docker run in practice: foreground and background containers, names, removing containers and passing commands.

Create a free account to save this page, take notes and track your progress. Sign in

docker run

docker run IMAGE [COMMAND] creates a container from an image and starts it. Useful options:

Option Meaning
--rm Remove the container when it exits
-d Run in the background (detached)
--name web Give it a name instead of a random one
-e KEY=value Set an environment variable
-p 8080:80 Publish container port 80 on host port 8080
-it Interactive terminal (for shells)

A container lives as long as its main process. When the command finishes, the container stops; with --rm it is also deleted.

Foreground, background and removal
docker run --rm -e GREETING=hi alpine:3.24 sh -c 'echo "$GREETING from $(hostname | cut -c1-4)..."; echo done' | sed 's/from [a-f0-9]*\.\.\./from <container id>/'
docker run -d --name rc-sleeper alpine:3.24 sleep 300 > /dev/null
docker ps --filter name=rc-sleeper --format '{{.Names}} is {{.State}} (image {{.Image}})'
docker rm -f rc-sleeper > /dev/null
echo "containers named rc-sleeper after docker rm: $(docker ps -a --filter name=rc-sleeper -q | wc -l)"

Output

hi from <container id>
done
rc-sleeper is running (image alpine:3.24)
containers named rc-sleeper after docker rm: 0

Run this on your computer — see “Get Started” for setup.

Test yourself

A container you started with docker run exits immediately. Why?

  1. Docker crashed
  2. Its main process finished; a container runs only as long as its main process
  3. Containers always stop after 1 second
  4. The image was too large
Show answer

Answer: Its main process finished; a container runs only as long as its main process

Long-running services keep their main process in the foreground; one-off commands exit when done.

Was this page helpful?