Skillversitas

Docker Container Lifecycle

The container lifecycle: Created → Running → Paused → Stopped → Removed.

Lifecycle States

# Created
docker create --name mycontainer nginx

# Running
docker start mycontainer

# Paused
docker pause mycontainer
docker unpause mycontainer

# Stopped
docker stop mycontainer

# Removed
docker rm mycontainer

Restart Policies

# always: restart when it crashes
docker run -d --restart always myapp

# unless-stopped: restart unless manually stopped
docker run -d --restart unless-stopped myapp

# on-failure: restart if it fails
docker run -d --restart on-failure:5 myapp

# no: no restart
docker run -d --restart no myapp

Use Case: Lifecycle Management

# docker-compose.yml
version: '3.8'

services:
  api:
    build: ./backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 3s
      retries: 3

  database:
    image: postgres:15
    restart: unless-stopped
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  db-data:

Everyday Use Case

Case: A container crashes in production.

# Check the restart status
docker inspect --format='{{.RestartCount}}' api

# View the logs before the crash
docker logs --tail 100 api

# Restart manually
docker restart api

Cleanup Policy

# Delete stopped containers
docker container prune

# Delete all containers
docker rm -f $(docker ps -aq)

# Auto-remove on stop
docker run -d --rm myapp

Best Practices

  1. Use a restart policy: For fault tolerance
  2. Health checks: For problem detection
  3. Resource limits: Avoid resource leaks
  4. Auto-remove: For temporary containers

Conclusion

Understanding the container lifecycle is important for managing applications. Use restart policies and health checks for fault tolerance.