Docker_containers
Chapter 04: Docker Containers
Section titled “Chapter 04: Docker Containers”Containers are running instances of Docker images. This chapter covers creating, running, and managing Docker containers.
Container Lifecycle
Section titled “Container Lifecycle”┌─────────────────────────────────────────────────────────────────────────────┐│ Container Lifecycle │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌─────────┐ create ┌─────────┐ start ┌─────────┐ ││ │ Image │ ──────────────▶ │ Created │ ──────────────▶ │ Running │ ││ └─────────┘ └─────────┘ └────┬────┘ ││ │ ││ ┌─────────┐ stop │ │ run ││ │ Stopped │ ◀──────────────┤ │ process ││ └─────────┘ │ │ ││ │ │ ││ ┌─────────┐ kill │ ▼ ││ │ Dead │ ◀───────────────┤ ┌─────────┐ ││ └─────────┘ └───────────────────── │ Running │ ││ │ with │ ││ │ PID 1 │ ││ └─────────┘ ││ ││ Container States: Created → Running → Paused → Stopped → Deleted ││ │└─────────────────────────────────────────────────────────────────────────────┘Running Containers
Section titled “Running Containers”Basic Run Command
Section titled “Basic Run Command”# Run a container in interactive modedocker run -it ubuntu /bin/bash
# Run in detached mode (background)docker run -d nginx
# Run with custom namedocker run -d --name my-nginx nginx
# Run with port mappingdocker run -d -p 8080:80 nginx
# Run with volume mountdocker run -d -v /myapp:/app myappCommon Run Options
Section titled “Common Run Options”# Interactive with pseudo-TTYdocker run -it ubuntu bash
# Detached (background)docker run -d nginx
# Remove container when it exitsdocker run --rm ubuntu echo "Hello"
# Assign random host portdocker run -d -P nginx
# Set environment variablesdocker run -d -e DATABASE_URL=postgres://db:5432/app myapp
# Set container hostnamedocker run -d --hostname mycontainer nginxContainer Management
Section titled “Container Management”Listing Containers
Section titled “Listing Containers”# List running containersdocker ps
# List all containers (including stopped)docker ps -a
# List containers with full IDsdocker ps -a --no-trunc
# Format outputdocker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# Filter containersdocker ps --filter "status=exited"docker ps --filter "name=nginx"Container Commands
Section titled “Container Commands”# Start a stopped containerdocker start mycontainer
# Stop a running containerdocker stop mycontainer
# Restart a containerdocker restart mycontainer
# Pause container processesdocker pause mycontainer
# Unpause container processesdocker unpause mycontainer
# Kill container (SIGKILL)docker kill mycontainer
# Remove containerdocker rm mycontainer
# Force remove running containerdocker rm -f mycontainerContainer Inspection
Section titled “Container Inspection”# View container detailsdocker inspect mycontainer
# View container logsdocker logs mycontainer
# Follow logs in real-timedocker logs -f mycontainer
# View last N lines of logsdocker logs --tail 100 mycontainer
# View logs with timestampsdocker logs -t mycontainer
# Execute command in running containerdocker exec -it mycontainer bash
# Run additional process in containerdocker exec mycontainer ls -laContainer Networking
Section titled “Container Networking”Port Mapping
Section titled “Port Mapping”# Map container port to host portdocker run -d -p 8080:80 nginx # Host 8080 → Container 80docker run -d -p 8081:80 nginx # Multiple containers
# Map to specific IPdocker run -d -p 127.0.0.1:8080:80 nginx
# Map to random available portdocker run -d -P nginx
# View port mappingsdocker port mycontainerNetwork Types
Section titled “Network Types”┌─────────────────────────────────────────────────────────────────────────────┐│ Docker Network Types │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌──────────────────┐ ││ │ Bridge │ Default network for standalone containers ││ │ │ Containers on same bridge can communicate ││ └──────────────────┘ ││ ││ ┌──────────────────┐ ││ │ Host │ Container shares host's network namespace ││ │ │ No network isolation from host ││ └──────────────────┘ ││ ││ ┌──────────────────┐ ││ │ Overlay │ Multi-host networking (Docker Swarm) ││ │ │ Containers across hosts can communicate ││ └──────────────────┘ ││ ││ ┌──────────────────┐ ││ │ None │ No networking - completely isolated ││ └──────────────────┘ ││ ││ ┌──────────────────┐ ││ │ Macvlan │ Container gets MAC address on physical network ││ │ │ Appears as physical device on network ││ └──────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘Container Resource Management
Section titled “Container Resource Management”Memory Limits
Section titled “Memory Limits”# Set memory limitdocker run -d --memory 512m nginx
# Set memory reservationdocker run -d --memory-reservation 256m nginx
# Set memory and swap limitdocker run -d --memory 512m --memory-swap 1g nginxCPU Limits
Section titled “CPU Limits”# Limit CPU to 1 coredocker run -d --cpus=1 nginx
# Limit to specific coresdocker run -d --cpuset-cpus=0,1 nginx
# Limit CPU share (default 1024)docker run -d --cpu-shares 512 nginxViewing Resource Usage
Section titled “Viewing Resource Usage”# View container stats (real-time)docker stats
# View stats for specific containerdocker stats mycontainer
# View stats in non-streaming modedocker stats --no-stream mycontainerContainer Logs
Section titled “Container Logs”# View logsdocker logs mycontainer
# Follow logsdocker logs -f mycontainer
# View last 50 linesdocker logs --tail 50 mycontainer
# View logs with timestampsdocker logs -t mycontainer
# Since timestampdocker logs --since 2024-01-01T10:00:00 mycontainer
# View only stderr or stdoutdocker logs --stderr mycontainerdocker logs --stdout mycontainerContainer Cleanup
Section titled “Container Cleanup”# Remove stopped containersdocker container prune
# Remove all stopped containersdocker rm $(docker ps -aq)
# Remove all containers (including running)docker rm -f $(docker ps -aq)
# Remove containers older than 24 hoursdocker container prune --filter "until=24h"Container Health Checks
Section titled “Container Health Checks”Docker can monitor container health using health checks:
FROM nginx:latestHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost/ || exit 1# Check container health statusdocker inspect --format='{{.State.Health.Status}}' mycontainerEnvironment Variables
Section titled “Environment Variables”# Set environment variabledocker run -d -e MY_VAR=value nginx
# Set multiple variablesdocker run -d -e DB_HOST=db -e DB_PORT=5432 myapp
# Pass from host environmentdocker run -d -e HOST_VAR myapp
# Use .env filedocker run -d --env-file .env myappContainer Entry Point
Section titled “Container Entry Point”# Override entrypointdocker run -d --entrypoint /bin/sh myapp
# Run with argumentsdocker run myapp arg1 arg2Common Container Patterns
Section titled “Common Container Patterns”Running a Web Server
Section titled “Running a Web Server”docker run -d \ --name nginx-web \ -p 80:80 \ -v /var/www/html:/usr/share/nginx/html:ro \ nginx:latestRunning a Database
Section titled “Running a Database”docker run -d \ --name postgres-db \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=mydb \ -v postgres-data:/var/lib/postgresql/data \ postgres:15Running a Development Environment
Section titled “Running a Development Environment”docker run -it \ --name dev-env \ -v $(pwd):/workspace \ -p 3000:3000 \ node:18 \ bashContainer Debugging
Section titled “Container Debugging”# Run container with interactive shelldocker run -it --rm ubuntu bash
# Inspect running processdocker top mycontainer
# Get detailed container infodocker inspect mycontainer
# Check container eventsdocker events
# Copy files from containerdocker cp mycontainer:/app/logs ./logsSummary
Section titled “Summary”In this chapter, you learned:
- Container lifecycle and states
- Running containers with various options
- Container management commands
- Network configuration
- Resource limits and monitoring
- Logging and debugging