Monitoring Containers
12. Monitoring Containers
Section titled “12. Monitoring Containers”📊 Built-in Monitoring Commands
Section titled “📊 Built-in Monitoring Commands”# Live stats for all containersdocker stats
# One-time snapshot (scriptable)docker stats --no-stream --format \ "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}"
# View logs with timestampsdocker logs -f --timestamps api
# Top processes inside a containerdocker top api
# Container events streamdocker events --filter type=container🏥 Health Checks
Section titled “🏥 Health Checks”# ── In Dockerfile ────────────────────────────────────────────HEALTHCHECK --interval=30s \ --timeout=10s \ --start-period=15s \ --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1# ── In docker-compose.yml ────────────────────────────────────services: api: healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 30s timeout: 10s retries: 3 start_period: 15s# Check health statusdocker ps # Shows (healthy) or (unhealthy)docker inspect api | grep -A 10 '"Health"'📈 Prometheus + Grafana Stack
Section titled “📈 Prometheus + Grafana Stack”services:
prometheus: image: prom/prometheus:latest volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml - prometheus-data:/prometheus ports: - "9090:9090" command: - '--config.file=/etc/prometheus/prometheus.yml'
grafana: image: grafana/grafana:latest ports: - "3001:3000" volumes: - grafana-data:/var/lib/grafana environment: GF_SECURITY_ADMIN_PASSWORD: admin
cadvisor: image: gcr.io/cadvisor/cadvisor:latest volumes: - /:/rootfs:ro - /var/run:/var/run:ro - /sys:/sys:ro - /var/lib/docker/:/var/lib/docker:ro ports: - "8080:8080"
volumes: prometheus-data: grafana-data:prometheus.yml:
global: scrape_interval: 15s
scrape_configs: - job_name: 'cadvisor' static_configs: - targets: ['cadvisor:8080']
- job_name: 'api' static_configs: - targets: ['api:3000'] # Your app's /metrics endpoint