Container Lifecycle Management
Manage the full Docker container lifecycle: create, start, stop, restart, pause, unpause, and remove containers. Learn restart policies and graceful shutdown.
Detailed Explanation
The Container Lifecycle
Docker containers go through several states: created, running, paused, stopped, and removed. Understanding this lifecycle is key to managing containers effectively.
Starting and Stopping
# Stop a running container (sends SIGTERM, then SIGKILL after 10s)
docker stop my-app
# Stop with custom timeout (30 seconds for graceful shutdown)
docker stop -t 30 my-app
# Start a stopped container
docker start my-app
# Restart (stop + start)
docker restart my-app
Restart Policies
Restart policies determine what happens when a container crashes or the Docker daemon restarts:
# Always restart (even after daemon restart)
docker run -d --restart=always my-app
# Restart on failure with max 5 retries
docker run -d --restart=on-failure:5 my-app
# Restart unless manually stopped
docker run -d --restart=unless-stopped my-app
Batch Operations
Stop all running containers:
docker stop $(docker ps -q)
Remove all stopped containers:
docker container prune -f
Pausing and Unpausing
Pause freezes all processes in a container using cgroups without terminating them:
docker pause my-app
docker unpause my-app
This is useful when you need to temporarily free resources without losing container state.
Use Case
Managing production services that need graceful shutdown, configuring restart policies for fault-tolerant deployments, and performing batch container operations during maintenance windows.