Container Lifecycle Management
Containers, like processes, have a complete lifecycle—understanding container state transitions and operational commands is a fundamental skill for Docker operations.
1. What You'll Learn
- The Six States of a Container and Their Transitions
- Start/Stop/Restart Operations
- The Difference Between Pausing and Resuming
- Viewing and Filtering Container Logs
- Troubleshooting Container Processes and Resources
2. A True Story of an Operations Engineer
(1) Pain Point: Production containers crash in the early morning
Charlie’s production container suddenly crashed at 3 a.m. A monitoring alert went off, but Charlie didn’t know why the container had exited—was it an OOM error? An application exception? Or had it been manually terminated? He needed to quickly troubleshoot the issue without having to rebuild the container.
(2) Solutions for Logging and Monitoring
docker logs displayed an OOM error, and docker stats confirmed the memory overflow.
# Check container exit logs
docker logs --tail 50 myapp
# Check container resource usage
docker stats --no-stream
(3) Benefit: Identify the root cause in 5 minutes
Charlie detected an "Out of memory" error using docker logs, docker inspect confirmed the exit code was 137 (OOM Kill), and the container returned to normal after adjusting the --memory parameter. It took only 5 minutes from the alert to the resolution.
3. The Six States of a Container
From creation to deletion, a container goes through six states.
stateDiagram-v2
[*] --> Created : docker create
Created --> Running : docker start
Created --> Running : docker run
Running --> Paused : docker pause
Paused --> Running : docker unpause
Running --> Stopped : docker stop / Ctrl+C
Running --> Stopped : docker kill
Stopped --> Running : docker start
Running --> Restarting : Process crash + restart policy
Restarting --> Running : Restart succeeds
Restarting --> Stopped : Restart fails
Running --> Dead : Unrecoverable error
Stopped --> [*] : docker rm
Dead --> [*] : docker rm
(1) Detailed Explanation of States
| Status | Description | Common Triggers |
|---|---|---|
| Created | Created but not started | docker create / docker run (not yet started) |
| Running | Running | docker start / docker run -d |
| Paused | Paused (process frozen) | docker pause |
| Stopped | Stopped(Exited) | docker stop / docker kill / Process Exit |
| Restarting | Restarting | Container crash + restart policy triggered |
| Dead | Unrecoverable | Internal Docker error (extremely rare) |
(2) View container status
# List running containers (Running state only)
docker ps
# List all containers (all states)
docker ps -a
# Filter by status
docker ps -a --filter "status=exited"
docker ps -a --filter "status=running"
4. Start, Stop, and Restart
▶ Example:start / stop / restart(Difficulty⭐)
# Create and start a container
docker run -d --name web -p 8080:80 nginx:latest
# Stop the container (graceful shutdown)
docker stop web
# Start it again
docker start web
# Restart (stop + start in one command)
docker restart web
# Check status after each operation
docker ps -a --filter name=web
(1) docker stop vs docker kill
| Dimension | docker stop |
docker kill |
|---|---|---|
| Signal | SIGTERM → Wait → SIGKILL | SIGKILL(Default) |
| Elegant | ✅ Give the app 30 seconds to clean up | ❌ Force quit immediately |
| Data Security | The application can write data and close the connection | Data that has not been written may be lost |
| Wait Time | Default 30 seconds (-t adjustable) |
No wait |
| Use Cases | Normal Shutdown | Force Termination When Container Is Unresponsive |
# Graceful stop with custom timeout (60 seconds)
docker stop -t 60 web
# Force kill immediately
docker kill web
# Send a custom signal
docker kill -s SIGUSR1 web
docker stop by default; use docker kill only if the container is unresponsive. The application should properly handle the SIGTERM signal to ensure a graceful shutdown.
5. Pausing and Resuming
▶ Example:pause / unpause(Difficulty⭐⭐)
# Pause the container (freeze all processes)
docker pause web
# Check: status should be "Paused"
docker ps -a --filter name=web
# Unpause the container
docker unpause web
(1) docker pause vs docker stop
| Dimension | docker pause |
docker stop |
|---|---|---|
| Mechanism | Freeze process (cgroup freeze) | Send a SIGTERM signal |
| Memory | Remains in memory | Memory is released |
| Recovery Speed | Immediate (thaw) | Requires process restart |
| Port in Use | Still in Use | Released |
| Use Cases | Temporarily freeing up CPU resources, debugging | Shutting down the service normally |
docker stop when you need to free up resources.
6. Viewing Container Logs
▶ Example: Real-time Container Log Monitoring (Difficulty: ⭐⭐)
# Follow logs in real-time
docker logs -f web
# Show last 100 lines
docker logs --tail 100 web
# Show logs from the last 2 hours
docker logs --since 2h web
# Show logs between specific times
docker logs --since "2024-01-15T10:00:00" --until "2024-01-15T12:00:00" web
10.0.0.1 - - [15/Jan/2024:10:05:22 +0000] "GET / HTTP/1.1" 200 615
10.0.0.1 - - [15/Jan/2024:10:05:23 +0000] "GET /favicon.ico HTTP/1.1" 404 555
(1) Log Parameter Quick Reference Table
| Parameter | Function | Example |
|---|---|---|
-f / --follow |
Real-time Tracking | docker logs -f web |
--tail N |
Show the last N lines | --tail 100 |
--since |
Display logs from a specific time onward | --since 2h / --since "2024-01-15" |
--until |
Display logs from before a certain time | --until 30m |
-t / --timestamps |
Show timestamp | docker logs -t web |
7. Container Resource Monitoring and Troubleshooting
▶ Example: Real-time Monitoring of Container Resources (Difficulty: ⭐⭐)
# Real-time resource stats for all containers
docker stats
# One-time snapshot (no streaming)
docker stats --no-stream
# Stats for a specific container
docker stats web --no-stream
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
a1b2c3d4e5f6 web 0.02% 4.2MiB / 512MiB 0.82% 1.2kB / 0B 0B / 0B 9
▶ Example: Viewing processes inside a container (Difficulty: ⭐)
# List processes running inside a container
docker top web
UID PID PPID C STIME TTY TIME CMD
root 1234 5678 0 10:05 ? 00:00:00 nginx: master process
www 1235 1234 0 10:05 ? 00:00:00 nginx: worker process
▶ Example: Viewing Detailed Container Configuration (Difficulty: ⭐⭐)
# Full container configuration (JSON)
docker inspect web
# Extract specific fields
docker inspect web --format='{{.State.Status}}'
docker inspect web --format='{{.State.ExitCode}}'
docker inspect web --format='{{.NetworkSettings.IPAddress}}'
docker inspect web --format='{{.HostConfig.Memory}}'
running
0
172.17.0.2
536870912
8. Enter a Running Container
▶ Example: Entering a container using docker exec (Difficulty: ⭐⭐)
# Open an interactive shell inside a running container
docker exec -it web bash
# Run a single command inside the container
docker exec web cat /etc/nginx/nginx.conf
# Copy files from container to host
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
docker exec does not create a new container; instead, it starts a new process within a running container. This is suitable for debugging and temporary operations. Avoid relying on docker exec in production environments—use volume mounts and log collection instead.
9. Complete Example: Simulating Container Troubleshooting
# ============================================
# Complete walkthrough: Container crash diagnosis
# Covers: run, crash, logs, inspect, fix, restart
# ============================================
# 1. Start a container with limited memory
docker run -d \
--name crash-test \
--memory=50m \
--restart=on-failure:3 \
nginx:latest
# 2. Verify it's running
docker ps --filter name=crash-test
# 3. Simulate memory pressure from inside the container
docker exec -it crash-test bash -c "dd if=/dev/zero of=/tmp/bigfile bs=1M count=100"
# 4. Container may be OOM-killed, check status
docker ps -a --filter name=crash-test
# 5. Check the exit code (137 = OOM Kill)
docker inspect crash-test --format='ExitCode: {{.State.ExitCode}}, OOMKilled: {{.State.OOMKilled}}'
# 6. Check logs for the crash reason
docker logs --tail 20 crash-test
# 7. Check Docker events for OOM
docker events --filter event=oom --since 5m
# 8. Fix: increase memory limit (need to recreate)
docker stop crash-test
docker rm crash-test
docker run -d \
--name crash-test \
--memory=256m \
--restart=on-failure:3 \
nginx:latest
# 9. Verify the fix
docker ps --filter name=crash-test
docker stats crash-test --no-stream
# docker inspect --format
ExitCode: 137, OOMKilled: true
# docker events
2024-01-15T10:05:22Z container oom crash-test...
# After fix
CONTAINER ID IMAGE STATUS NAMES
b2c3d4e5f6a7 nginx:latest Up 10 seconds crash-test
❓ FAQ
docker start. However, the data will be lost after deleting the container with docker rm—unless a volume is mounted.docker stop and docker kill?stop sends a SIGTERM signal, giving the application 30 seconds to shut down gracefully (to complete writes and close connections); if it times out, it sends a SIGKILL signal. kill sends a SIGKILL signal immediately to terminate the process. In a production environment, use stop whenever possible; use kill only when the container is unresponsive.--restart=always or --restart=unless-stopped when starting the container. "always" restarts the container regardless of the reason for termination; "unless-stopped" prevents automatic restart after a manual stop. unless-stopped is recommended for production web services.json-file, does not automatically rotate logs, so logs may grow indefinitely. Configure log limits at startup: docker run --log-opt max-size=10m --log-opt max-file=3, which limits each log file to 10 MB and retains a maximum of 3 files.docker exec -it <container> bash (or sh). This is the most common debugging method. If the container does not have bash, use docker exec -it <container> sh. You can also use docker attach to connect, but it connects to the main process’s stdin, and pressing Ctrl+C will stop the container, so it is generally not used.📖 Summary
- Six Container States::Created / Running / Paused / Stopped / Restarting / Dead
docker stopGraceful shutdown (SIGTERM),docker killForced termination (SIGKILL)docker pauseFreeze the process and retain memory;docker stopRelease memorydocker logsSupports-freal-time tracking,--since/--untiltime filtering, and--tailrow limitsdocker statsMonitor resources,docker topView processes,docker inspectView configuration- Exit code 137 = OOM Kill, a key clue for troubleshooting container issues
📝 Exercises
- Basic Exercise (Difficulty ⭐): After starting the Nginx container, stop it using
docker stop, then restart it usingdocker start, and record the status changes displayed bydocker ps -aafter each operation. - Advanced Exercise (Difficulty ⭐⭐): Use
docker logs --tail 50 -fto view the Nginx container logs in real time. Visithttp://localhost:808010 times in your browser and observe the request entries in the logs. - Challenge (Difficulty: ⭐⭐⭐): Use
docker exec -itto access the Nginx container, modify the contents of/usr/share/nginx/html/index.html, and then visit the page in your browser to confirm that the changes have taken effect. Think about it: Will the changes be retained after the container is deleted? How can you make the changes persistent?



