What are container lifecycle management commands (docker run, stop, start, restart, rm, kill)?
❓ Interview Prompt: Explain the Docker container lifecycle from creation to deletion, including SIGTERM graceful shutdown vs SIGKILL.
Docker containers follow a well-defined lifecycle from creation to removal:
Lifecycle States:
Created → Running → Stopped (Exited) → Removed
Key Commands:
| Command | Action | Signal Sent |
|---|---|---|
| docker run | Create + start a new container | — |
| docker start | Start a stopped container | — |
| docker stop | Gracefully stop (10s timeout) | SIGTERM → SIGKILL |
| docker kill | Forcefully terminate immediately | SIGKILL (or custom) |
| docker pause | Freeze container processes | SIGSTOP (cgroup) |
| docker unpause | Resume frozen container | SIGCONT |
| docker restart | Stop + start in one command | SIGTERM → SIGKILL |
| docker rm | Delete a stopped container | — |
| docker rm -f | Force-delete a running container | SIGKILL then delete |
Graceful Shutdown:
docker stop sends SIGTERM first, giving the app 10 seconds to clean up connections and flush buffers. After 10 seconds, Docker sends SIGKILL to force-terminate. Override the timeout with --time 30.
Code Implementation Example
# Create and start (background detached mode)
docker run -d --name myapi -p 3000:3000 myapp:latest
# View running containers
docker ps
# Graceful stop — sends SIGTERM, waits 10s, then SIGKILL
docker stop myapi
# Force kill immediately — sends SIGKILL
docker kill myapi
# View all containers including stopped
docker ps -a
# Restart a container
docker restart myapi
# Remove stopped container
docker rm myapi
# One-liner: force-remove running container
docker rm -f myapi
# Clean up ALL stopped containers
docker container prunedocker stop sends SIGTERM for graceful shutdown (app closes connections); docker kill sends SIGKILL immediately. Always prefer docker stop for production containers.