Container Lifecycle
A Docker container goes through several states during its lifecycle: Created → Running → Paused → Stopped → Removed. Understanding these states helps you manage containers effectively.
Creating and Running Containers
# Run a container (pull + create + start)
docker run nginx
# Run in detached mode (background)
docker run -d nginx
# Run with a name
docker run -d --name my-web nginx
# Run with port mapping
docker run -d -p 8080:80 --name my-web nginx
# Run with environment variables
docker run -d \
--name my-app \
-e NODE_ENV=production \
-e DB_HOST=localhost \
-p 3000:3000 \
myapp:latest
# Run interactively with a shell
docker run -it ubuntu bash
docker run -it node:20-alpine sh
Managing Running Containers
# List running containers
docker ps
# List all containers (including stopped)
docker ps -a
# Stop a container gracefully (SIGTERM then SIGKILL)
docker stop my-web
# Start a stopped container
docker start my-web
# Restart a container
docker restart my-web
# Pause / Unpause
docker pause my-web
docker unpause my-web
# Kill a container immediately (SIGKILL)
docker kill my-web
Inspecting Containers
# View container logs
docker logs my-web
docker logs -f my-web # Follow logs (like tail -f)
docker logs --tail 50 my-web # Last 50 lines
# Get detailed container info
docker inspect my-web
# Get specific info using Go templates
docker inspect --format='{{.State.Status}}' my-web
docker inspect --format='{{.NetworkSettings.IPAddress}}' my-web
# View resource usage (CPU, memory, I/O)
docker stats
docker stats my-web
# See running processes inside a container
docker top my-web
Executing Commands in Containers
# Run a command inside a running container
docker exec my-web ls /usr/share/nginx/html
# Open an interactive shell
docker exec -it my-web bash
docker exec -it my-web sh
# Run a command as a specific user
docker exec -u root my-web whoami
# Copy files to/from a container
docker cp my-web:/etc/nginx/nginx.conf ./nginx.conf
docker cp ./index.html my-web:/usr/share/nginx/html/
Removing Containers
# Remove a stopped container
docker rm my-web
# Force remove a running container
docker rm -f my-web
# Remove all stopped containers
docker container prune
# Run a container that auto-removes on exit
docker run --rm -it ubuntu bash
Container Resource Limits
# Limit memory
docker run -d --memory="512m" --name limited-app myapp
# Limit CPU
docker run -d --cpus="1.5" --name limited-app myapp
# Limit both
docker run -d \
--memory="1g" \
--cpus="2" \
--name prod-app \
myapp:latest
# Update limits on a running container
docker update --memory="1g" --cpus="2" my-app
Key Takeaways
- ✅ Use
-dfor background containers and-itfor interactive sessions - ✅ Always name containers with
--namefor easier management - ✅ Use
docker logs -fto monitor container output in real time - ✅ Set resource limits in production to prevent one container from consuming all resources