Container Management
Container Lifecycle Overview
Docker containers have a defined lifecycle with multiple states, from creation to termination. Understanding these states is crucial for effective container management.
stateDiagram-v2
[*] --> Created
Created --> Running
Running --> Paused
Paused --> Running
Running --> Stopped
Stopped --> Removed
Removed --> [*]
Basic Container Operations
Container Management Commands
Command |
Function |
Example |
docker create |
Create a container |
docker create nginx |
docker start |
Start a container |
docker start container_id |
docker stop |
Stop a running container |
docker stop container_id |
docker restart |
Restart a container |
docker restart container_id |
docker rm |
Remove a container |
docker rm container_id |
Running Containers
## Run container in foreground
docker run nginx
## Run container in background
docker run -d nginx
## Run container with port mapping
docker run -p 8080:80 nginx
## Run container with custom name
docker run --name web-server nginx
Container Inspection and Monitoring
## List running containers
docker ps
## List all containers
docker ps -a
## View container logs
docker logs container_id
## Inspect container details
docker inspect container_id
## Monitor container resource usage
docker stats
Container Networking
## List docker networks
docker network ls
## Create custom network
docker network create mynetwork
## Connect container to network
docker network connect mynetwork container_id
Advanced Container Management
Container Resource Limits
## Limit CPU and memory
docker run -d \
--cpus="1.5" \
--memory="512m" \
nginx
Container Scaling
## Create multiple container instances
docker run -d -p 8001:80 nginx
docker run -d -p 8002:80 nginx
docker run -d -p 8003:80 nginx
Container Deployment Strategies
Persistent Data Management
## Create volume
docker volume create myvolume
## Mount volume to container
docker run -v myvolume:/app/data nginx
Environment Configuration
## Set environment variables
docker run -e DATABASE_URL=localhost nginx