Container Lifecycle
Understanding the container lifecycle helps you manage containers effectively. Containers transition through several states from creation to removal.
Container States
A container can be in one of several states:
┌──────────┐ ┌─────────┐ ┌──────────┐
│ Created │────▶│ Running │────▶│ Exited │
└──────────┘ └─────────┘ └──────────┘
│ │
│ │
▼ ▼
┌─────────┐ ┌──────────┐
│ Paused │ │ Removed │
└─────────┘ └──────────┘
| State | Description |
|---|---|
| Created | Container exists but hasn't started |
| Running | Container is executing |
| Paused | Container execution is suspended |
| Exited | Container has stopped (success or failure) |
| Removing | Container is being deleted |
Creating vs Running
You can create a container without starting it:
# Create only (doesn't start)
docker create --name mycontainer nginx
# Check status
docker ps -a
# STATUS: Created
# Start the container
docker start mycontainer
# Check status again
docker ps
# STATUS: Up X seconds
Compare with docker run which creates AND starts:
# Create and start in one command
docker run -d --name mycontainer nginx
Lifecycle Commands
Starting and Stopping
# Start a stopped container
docker start container_name
# Stop a running container (SIGTERM, then SIGKILL after 10s)
docker stop container_name
# Stop with custom timeout
docker stop -t 30 container_name
# Force stop immediately (SIGKILL)
docker kill container_name
Restarting
# Restart a container
docker restart container_name
# Restart with timeout
docker restart -t 5 container_name
Pausing and Unpausing
# Pause a container (freeze all processes)
docker pause container_name
# Unpause
docker unpause container_name
Pausing is useful for:
- Temporarily freeing CPU resources
- Taking consistent filesystem snapshots
- Debugging without stopping the container
Viewing Container Status
List Containers
# Running containers only
docker ps
# All containers (including stopped)
docker ps -a
# Just container IDs
docker ps -q
# With size information
docker ps -s
# Custom format
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
Inspect Container Details
# Full container information (JSON)
docker inspect container_name
# Specific field
docker inspect -f '{{.State.Status}}' container_name
# Network settings
docker inspect -f '{{.NetworkSettings.IPAddress}}' container_name
# Mounted volumes
docker inspect -f '{{.Mounts}}' container_name
Container Logs
Containers capture stdout and stderr:
# View all logs
docker logs container_name
# Follow logs in real-time
docker logs -f container_name
# Last N lines
docker logs --tail 50 container_name
# Include timestamps
docker logs -t container_name
# Logs since a specific time
docker logs --since 10m container_name
docker logs --since 2024-01-01T00:00:00 container_name
Exit Codes
When a container exits, it returns an exit code:
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 125 | Docker daemon error |
| 126 | Command cannot be invoked |
| 127 | Command not found |
| 128+n | Fatal signal n (e.g., 137 = killed by SIGKILL) |
Check exit codes:
# Run and check exit code
docker run ubuntu exit 42
echo $? # Output: 42
# Inspect exit code
docker inspect -f '{{.State.ExitCode}}' container_name
Restart Policies
Configure automatic restart behavior:
# Never restart (default)
docker run --restart no myimage
# Always restart
docker run --restart always myimage
# Restart unless manually stopped
docker run --restart unless-stopped myimage
# Restart on failure (with max attempts)
docker run --restart on-failure:5 myimage
| Policy | Behavior |
|---|---|
| no | Never restart |
| always | Always restart (including after daemon restart) |
| unless-stopped | Restart unless manually stopped |
| on-failure[:n] | Restart only on non-zero exit (max n times) |
Container Health Checks
Define health checks to monitor container status:
# Run with health check
docker run -d \
--health-cmd="curl -f http://localhost/ || exit 1" \
--health-interval=30s \
--health-timeout=10s \
--health-retries=3 \
nginx
Health states:
- starting: Health check not yet run
- healthy: Passing health checks
- unhealthy: Failing health checks
Resource Monitoring
Monitor container resource usage:
# Real-time stats
docker stats
# Stats for specific containers
docker stats container1 container2
# One-time snapshot
docker stats --no-stream
# Custom format
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
Container Events
Watch Docker events in real-time:
# All events
docker events
# Events for specific container
docker events --filter container=mycontainer
# Filter by event type
docker events --filter event=start --filter event=stop
# Since a specific time
docker events --since 1h
Removing Containers
# Remove a stopped container
docker rm container_name
# Force remove (even if running)
docker rm -f container_name
# Remove all stopped containers
docker container prune
# Remove all stopped containers (alternative)
docker rm $(docker ps -aq)
Container Lifecycle Example
Here's a complete lifecycle walkthrough:
# 1. Create container
docker create --name lifecycle-demo nginx
docker ps -a | grep lifecycle-demo
# STATUS: Created
# 2. Start container
docker start lifecycle-demo
docker ps | grep lifecycle-demo
# STATUS: Up X seconds
# 3. Pause container
docker pause lifecycle-demo
docker ps | grep lifecycle-demo
# STATUS: Up X seconds (Paused)
# 4. Unpause container
docker unpause lifecycle-demo
docker ps | grep lifecycle-demo
# STATUS: Up X seconds
# 5. Stop container
docker stop lifecycle-demo
docker ps -a | grep lifecycle-demo
# STATUS: Exited (0) X seconds ago
# 6. Restart container
docker start lifecycle-demo
docker ps | grep lifecycle-demo
# STATUS: Up X seconds
# 7. Remove container
docker rm -f lifecycle-demo
docker ps -a | grep lifecycle-demo
# (no output - container removed)
Key Takeaways
- Containers transition through Created, Running, Paused, Exited, and Removed states
- Use
docker createanddocker startseparately, ordocker runfor both docker stopsends SIGTERM;docker killsends SIGKILL- Configure restart policies for automatic recovery
- Use health checks to monitor container status
- Exit codes indicate why a container stopped
docker ps -ashows all containers including stopped ones- Clean up unused containers with
docker container prune
التالي · الدرس 7 من 32
Understanding Docker Images
قراءة 4 دقيقة
أنهيت 6 من 32 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

