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


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.

BASH
# 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.

100%
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

BASH
# 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⭐)

BASH
# 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
BASH
# 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
💡 Tip: In production environments, use 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⭐⭐)

BASH
# 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
⚠️ Note: Paused containers still consume memory and ports, so they should not be left paused for long periods. Use docker stop when you need to free up resources.


6. Viewing Container Logs

▶ Example: Real-time Container Log Monitoring (Difficulty: ⭐⭐)

BASH
# 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
💻 Output:

TEXT
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: ⭐⭐)

BASH
# 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
💻 Output:

TEXT
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: ⭐)

BASH
# List processes running inside a container
docker top web
💻 Output:

TEXT
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: ⭐⭐)

BASH
# 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}}'
💻 Output:

TEXT
running
0
172.17.0.2
536870912

8. Enter a Running Container

▶ Example: Entering a container using docker exec (Difficulty: ⭐⭐)

BASH
# 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
💡 Tip: 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

BASH
# ============================================
# 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
💻 Output (excerpt):

TEXT
# 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

Q Is the data still there after the container stops?
A Yes. Stopping the container merely pauses the process; the file system remains on the disk. You can restore it using docker start. However, the data will be lost after deleting the container with docker rm—unless a volume is mounted.
Q What is the difference between docker stop and docker kill?
A 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.
Q How can I set a container to automatically restart after it crashes?
A Add --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.
Q What should I do if container log files are too large?
A Docker’s default log driver, 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.
Q How do I enter a running container?
A 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.
Q What does exit code 137 mean?
A 137 = 128 + 9, where 9 is the signal number for SIGKILL. When a container is killed by the OOM Killer, the exit code is 137. Other common exit codes: 0 = normal exit, 1 = application error, 2 = command misuse, 125 = Docker daemon error.

📖 Summary


📝 Exercises

  1. Basic Exercise (Difficulty ⭐): After starting the Nginx container, stop it using docker stop, then restart it using docker start, and record the status changes displayed by docker ps -a after each operation.
  2. Advanced Exercise (Difficulty ⭐⭐): Use docker logs --tail 50 -f to view the Nginx container logs in real time. Visit http://localhost:8080 10 times in your browser and observe the request entries in the logs.
  3. Challenge (Difficulty: ⭐⭐⭐): Use docker exec -it to 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?
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏