Container Lifecycle
Running a container
Section titled “Running a container”docker run is the most common command you will use. It pulls the image if needed, creates a container, and starts it.
docker run nginx:alpineThis runs nginx in the foreground — your terminal attaches to its output. Press Ctrl+C to stop it.
Detached mode with -d
Section titled “Detached mode with -d”Add -d to run the container in the background:
docker run -d nginx:alpineDocker prints the full container ID and returns your prompt immediately.
Naming a container with --name
Section titled “Naming a container with --name”By default Docker assigns a random name. Use --name to give it a predictable one:
docker run -d --name webserver nginx:alpineListing containers
Section titled “Listing containers”# Only running containersdocker ps
# All containers — running AND stoppeddocker ps -aCONTAINER ID IMAGE STATUS NAMESa1b2c3d4e5f6 nginx:alpine Up 2 minutes webserverb7c8d9e0f1a2 alpine Exited (0) 5 minutes ago old-taskThe STATUS column tells you whether the container is running (Up) or stopped (Exited).
Stopping, starting, and restarting
Section titled “Stopping, starting, and restarting”# Graceful stop — sends SIGTERM, waits 10 s, then SIGKILLdocker stop webserver
# Start a stopped containerdocker start webserver
# Restart (stop then start)docker restart webserverdocker stop does not remove the container. It remains on disk in the stopped state.
Removing a container
Section titled “Removing a container”# Remove a stopped containerdocker rm webserver
# Force-remove a running container (sends SIGKILL)docker rm -f webserverYou cannot remove a running container without -f.
Auto-cleanup with --rm
Section titled “Auto-cleanup with --rm”For one-shot tasks you never want to manage manually, add --rm. The container is removed automatically the moment its process exits.
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"