Skip to content

Container Lifecycle

docker run is the most common command you will use. It pulls the image if needed, creates a container, and starts it.

Terminal window
docker run nginx:alpine

This runs nginx in the foreground — your terminal attaches to its output. Press Ctrl+C to stop it.

Add -d to run the container in the background:

Terminal window
docker run -d nginx:alpine

Docker prints the full container ID and returns your prompt immediately.

By default Docker assigns a random name. Use --name to give it a predictable one:

Terminal window
docker run -d --name webserver nginx:alpine
Terminal window
# Only running containers
docker ps
# All containers — running AND stopped
docker ps -a
CONTAINER ID IMAGE STATUS NAMES
a1b2c3d4e5f6 nginx:alpine Up 2 minutes webserver
b7c8d9e0f1a2 alpine Exited (0) 5 minutes ago old-task

The STATUS column tells you whether the container is running (Up) or stopped (Exited).

Terminal window
# Graceful stop — sends SIGTERM, waits 10 s, then SIGKILL
docker stop webserver
# Start a stopped container
docker start webserver
# Restart (stop then start)
docker restart webserver

docker stop does not remove the container. It remains on disk in the stopped state.

Terminal window
# Remove a stopped container
docker rm webserver
# Force-remove a running container (sends SIGKILL)
docker rm -f webserver

You cannot remove a running container without -f.

For one-shot tasks you never want to manage manually, add --rm. The container is removed automatically the moment its process exits.

Terminal window
docker run --rm alpine echo "Hello, Docker!"
Hello, Docker!

The container is gone as soon as the echo finishes — no docker rm needed.

# 1. Run nginx detached with a name
docker run -d --name webserver nginx:alpine

# 2. List running containers
docker ps

# 3. Stop it
docker stop webserver

# 4. Show all containers — notice STATUS is Exited
docker ps -a

# 5. Start it again
docker start webserver

# 6. Remove it (stop first)
docker stop webserver && docker rm webserver

# 7. One-shot: auto-cleanup with --rm
docker run --rm alpine echo "done — already gone"
What does 'docker stop' send to the container's main process first?
Which command shows ALL containers, including stopped ones?
What does the --rm flag do?
Can you remove a running container without the -f flag?