Intro
Docker Compose profiles allow you to define and run different sets of services for different environments, such as development, testing, and production. With multiple profiles and services, monitoring their health and performance becomes critical to ensure reliability. In this guide, we will explore how to monitor Docker Compose profiles, set up alerts, and create dashboards to keep your applications running smoothly. We will provide practical commands, configuration snippets, and examples to help you implement monitoring effectively.
By the end of this article, you will understand what to monitor, how to collect metrics, how to define alert rules, and how to respond to incidents. We will also cover a practical checklist to ensure your monitoring setup is robust and maintainable. Whether you are new to Docker Compose or looking to enhance your current monitoring, this guide offers actionable steps to improve observability.
Version and Environment Inventory
Before setting up monitoring, ensure your environment is properly inventoried. This includes recording the Docker Compose version, the services defined, and the profiles used. A clear inventory helps you understand what needs monitoring and establishes a baseline for performance.
Use the following command to check your Docker Compose version:
docker compose version
Example output:
Docker Compose version v2.20.2
Next, inspect your docker-compose.yml file to list profiles and services. Consider a compose file with a web service in the frontend profile and a database service in the backend profile:
services:
web:
image: nginx:latest
profiles: ["frontend"]
ports:
- "80:80"
db:
image: postgres:15
profiles: ["backend"]
environment:
POSTGRES_PASSWORD: example
To see which profiles are active and which services are running, use:
docker compose ps
Example output with only the backend profile enabled:
NAME COMMAND SERVICE STATUS PORTS
db-1 "docker-entrypoint.s…" db running 5432/tcp
Additionally, check container resource usage with docker stats to establish a baseline:
docker stats --no-stream
Example output:
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
abc123def456 db-1 0.50% 45.2MiB / 1.952GiB 2.26% 1.2kB / 0B 0B / 0B 12
Record these baseline metrics for later comparison. This baseline helps you determine normal operating ranges and set appropriate alert thresholds. Ensure you have the necessary permissions to run Docker commands and that your monitoring tooling can access the Docker daemon. Running these commands as a user in the docker group is common, but be mindful of security implications.
Consider using a script or a simple text file to document your environment. Include the Docker Compose version, the list of services with their profiles, and the baseline metrics. This documentation will be invaluable when troubleshooting or when onboarding new team members. For example, you might create an inventory.md file with the output of the commands above.
Safe Configuration Path
For monitoring Docker Compose profiles, a safe configuration path involves scoping your monitoring to specific profiles and using non-invasive methods. Start by exporting metrics from your containers. Many applications expose metrics on a specific port (e.g., Prometheus metrics). For services that do not natively expose metrics, use exporters like cadvisor for container metrics or node-exporter for host metrics.
Create a monitoring stack using Docker Compose itself, but place it in a separate profile to avoid interfering with your application profiles. For example, add a monitoring profile with Prometheus and Grafana:
services:
prometheus:
image: prom/prometheus:latest
profiles: ["monitoring"]
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- '--config.file=/etc/prometheus/prometheus.yml'
grafana:
image: grafana/grafana:latest
profiles: ["monitoring"]
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
Then, configure Prometheus to scrape metrics from your application services. In prometheus.yml, define scrape targets for each service. For services in the frontend profile, you might scrape the web service's metrics endpoint, if available, or use cadvisor to collect container-level metrics. Here is a sample prometheus.yml snippet:
scrape_configs:
- job_name: 'docker'
static_configs:
- targets: ['cadvisor:8080']
Additionally, you may want to scrape metrics from the Docker daemon itself. Docker exposes metrics on http://host.docker.internal:9323/metrics if you enable the metrics-address in the daemon configuration. However, using cadvisor is often simpler and provides per-container metrics.
This approach is safe because the monitoring services run only when you explicitly enable the monitoring profile. To enable the monitoring profile, run:
docker compose --profile monitoring up -d
Keep in mind that Prometheus and Grafana are stateful; you should mount volumes to persist data. For example:
volumes:
prometheus_data:
grafana_data:
services:
prometheus:
volumes:
- prometheus_data:/prometheus
grafana:
volumes:
- grafana_data:/var/lib/grafana
Consider using environment variables to configure alerting endpoints (e.g., Slack webhooks) without hardcoding secrets. In Grafana, you can set up alerting with environment variables like GF_SECURITY_ADMIN_PASSWORD as shown, but avoid committing sensitive values to version control. Use Docker secrets or a .env file that is gitignored.
For production environments, you may want to restrict access to the monitoring endpoints. Use network segmentation to ensure that only authorized users can access Prometheus and Grafana. For instance, you can bind the ports to localhost only by using 127.0.0.1:9090:9090 and access them through a reverse proxy with authentication.
Verification and Diagnostics
After configuring monitoring, verify that metrics are being collected and alerts are working. Check Prometheus targets by navigating to http://localhost:9090/targets or using the API:
curl http://localhost:9090/api/v1/targets
Example output snippet:
{
"status": "success",
"data": {
"activeTargets": [
{
"discoveredLabels": {},
"labels": {
"job": "docker"
},
"scrapeUrl": "http://cadvisor:8080/metrics",
"lastError": "",
"lastScrape": "2023-10-01T12:00:00Z",
"health": "up"
}
]
}
}
The health field should be up for all targets. If a target is down, inspect the lastError field for clues. Common errors include connection refused, DNS resolution failure, or authentication issues.
To query a metric, use PromQL. For example, to get CPU usage per container:
rate(container_cpu_usage_seconds_total{name=~".+"}[5m])
Expected output in Prometheus UI: a list of time series with container names and their CPU usage rates. You can also execute this query via the API:
curl 'http://localhost:9090/api/v1/query?query=rate(container_cpu_usage_seconds_total%7Bname%3D~%22.%2B%22%7D%5B5m%5D)'
The result will be in JSON format. Use a tool like jq to parse it if needed.
For log-based diagnostics, use docker logs on your application containers to check for errors. For example:
docker logs <container_name> --tail 50
Replace <container_name> with the actual container name from docker compose ps. Look for error patterns such as stack traces, connection timeouts, or configuration errors.
If you have configured alert rules in Prometheus, check the Alerts page or API to see if any alerts are firing:
curl http://localhost:9090/api/v1/alerts
Example output when an alert is firing:
{
"status": "success",
"data": {
"alerts": [
{
"labels": {
"alertname": "HighCPUUsage",
"container": "web"
},
"state": "firing",
"activeAt": "2023-10-01T12:05:00Z",
"annotations": {
"summary": "High CPU usage detected"
}
}
]
}
}
The state field can be inactive, pending, or firing. A pending state means the alert condition is met but has not yet lasted for the for duration.
To test alerting end-to-end, you can temporarily lower the threshold and trigger the condition manually. For example, generate CPU load on the web container using stress or by sending a burst of requests. Then verify that the alert fires and the notification is sent to your configured receiver (e.g., Slack).
Failure Modes and Recovery
Common failure modes in monitoring Docker Compose profiles include misconfigured scrape targets, insufficient permissions, and alert fatigue. Understanding these failure modes and how to recover from them is crucial for maintaining a reliable monitoring system.
Misconfigured scrape targets: This can happen due to incorrect target addresses, wrong ports, or missing network connectivity. To recover, verify the target's metrics endpoint is reachable from the Prometheus container. Use docker exec to test connectivity:
docker exec prometheus wget -qO- http://cadvisor:8080/metrics | head
If the connection fails, ensure the services are on the same Docker network. Define a custom network in your compose file and attach all services to it:
networks:
monitoring:
driver: bridge
services:
prometheus:
networks:
- monitoring
cadvisor:
networks:
- monitoring
web:
networks:
- monitoring
Also check that the target service is actually running and listening on the expected port. You can use docker exec to run netstat or ss inside the container.
Insufficient permissions: Some exporters require elevated privileges. For example, cadvisor usually needs access to the Docker socket or root privileges to collect metrics. If you see permission errors in the logs, adjust the container's privileges. Check the container logs:
docker logs cadvisor
You may need to add --privileged or mount specific volumes. However, be cautious with --privileged as it grants extensive capabilities. A safer approach is to mount only the required paths, such as /var/run/docker.sock for cadvisor:
cadvisor:
image: gcr.io/cadvisor/cadvisor:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /sys:/sys:ro
- /var/lib/docker/:/var/lib/docker:ro
Run cadvisor in read-only mode where possible to minimize security risks.
Alert fatigue: Alert fatigue occurs when alerts are too frequent or not actionable, causing teams to ignore them. To avoid this, tune alert thresholds based on baseline metrics and add for clauses to alerts so they only fire after a sustained condition. For example:
groups:
- name: example
rules:
- alert: HighCPUUsage
expr: rate(container_cpu_usage_seconds_total{name="web"}[5m]) > 0.8
for: 10m
labels:
severity: warning
annotations:
summary: "High CPU usage on web container"
The for: 10m ensures the alert only fires if the condition persists for 10 minutes, reducing transient alerts. Additionally, consolidate similar alerts and use severity levels to prioritize.
Recovery via rollback: If a monitoring configuration causes issues, disable the monitoring profile and revert to a previous configuration. For example:
docker compose --profile monitoring down
Then, restore the previous prometheus.yml from version control. Always use version control for your compose files and monitoring configurations to facilitate quick rollback. A Git repository with branches for changes and tags for releases is recommended.
Data loss: Prometheus and Grafana store data in volumes. If volumes are not backed up, you may lose metrics and dashboards. To recover, implement regular backups of the volumes. For example, use docker run --rm -v prometheus_data:/data -v $(pwd):/backup alpine tar czf /backup/prometheus_data.tar.gz /data. Schedule this backup using cron or a CI/CD pipeline.
Alerting and Notification Setup
Beyond defining alerts in Prometheus, you need to route notifications to your team. Use Alertmanager to handle alert routing, deduplication, and silencing. Add Alertmanager to your monitoring profile:
alertmanager:
image: prom/alertmanager:latest
profiles: ["monitoring"]
ports:
- "9093:9093"
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
command:
- '--config.file=/etc/alertmanager/alertmanager.yml'
Create an alertmanager.yml configuration to send alerts to Slack, email, or PagerDuty. Here is an example for Slack:
route:
receiver: 'slack-notifications'
group_by: ['alertname', 'cluster', 'service']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receivers:
- name: 'slack-notifications'
slack_configs:
- api_url: 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
channel: '#monitoring'
text: "{{ range .Alerts }}{{ .Annotations.summary }}\n{{ end }}"
Then, update Prometheus to send alerts to Alertmanager:
alerting:
alertmanagers:
- static_configs:
- targets:
- alertmanager:9093
Test the notification flow by triggering a test alert. You can use amtool to send a test alert to Alertmanager, or manually set an alert condition to fire and observe the Slack message.
For more advanced routing, you can define different receivers based on severity or service. For example, route critical alerts to PagerDuty and warning alerts to Slack. Use label matching in the route configuration.
Common Pitfalls and How to Avoid Them
While setting up monitoring, several pitfalls can undermine your efforts. Being aware of these pitfalls and knowing how to avoid them will save time and frustration.
Pitfall 1: Not version-controlling monitoring configurations
Why it happens: Monitoring configurations are often treated as afterthoughts and not included in version control. How to avoid: Store all configuration files (docker-compose.yml, prometheus.yml, alertmanager.yml, Grafana dashboards) in a Git repository. Use branches for changes and pull requests for review. This ensures you can track changes and roll back if needed.
Pitfall 2: Hardcoding secrets in configuration files
Why it happens: Developers may hardcode API keys or passwords for convenience. How to avoid: Use environment variables or secret management tools. In Docker Compose, use the env_file directive or Docker secrets. Never commit secrets to version control. For example:
services:
grafana:
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD}
Store the actual password in a .env file that is gitignored.
Pitfall 3: Monitoring too many metrics without clear purpose
Why it happens: Teams collect every available metric, leading to information overload and storage costs. How to avoid: Start with a small set of key metrics: CPU usage, memory usage, disk I/O, network traffic, and application-specific metrics that align with your SLOs. Consult the USE method (Utilization, Saturation, Errors) and RED method (Rate, Errors, Duration) to choose metrics. Gradually add more as needed.
Pitfall 4: Ignoring alert fatigue
Why it happens: Alerts are set too sensitively or without for clauses, resulting in frequent false positives. How to avoid: Set realistic thresholds based on baseline performance. Use for clauses to require sustained conditions. Regularly review alerts and adjust thresholds. Implement alert routing and silencing to reduce noise.
Pitfall 5: Not testing monitoring setup in staging
Why it happens: Teams often test monitoring only in production, leading to surprises. How to avoid: Replicate your monitoring stack in a staging environment using the same profiles. Test alerts, dashboards, and failover scenarios before deploying to production.
Pitfall 6: Neglecting security of monitoring endpoints
Why it happens: Prometheus and Grafana are often left exposed without authentication, assuming internal network safety. How to avoid: Always enable authentication in Grafana (default is admin/admin, but change it). For Prometheus, use a reverse proxy with basic auth or TLS. Use network policies to restrict access.
Operations Checklist
Use this checklist to ensure your monitoring setup is operational and maintained. Assign a single accountable owner to each task to ensure responsibility and follow-through. Review the checklist weekly or after any significant change to the environment.
| Task | Command / Check | Expected Result | Owner | Frequency |
|---|---|---|---|---|
| Verify Docker Compose version | docker compose version | Version v2.20.2 or later | DevOps Engineer (e.g., Alex Chen) | Monthly |
| Check active profiles and services | docker compose ps | List of running services with their profiles | Sysadmin (e.g., Maria Garcia) | Daily |
| Validate Prometheus configuration | promtool check config prometheus.yml | No syntax errors | Monitoring Lead (e.g., Sam Patel) | Before each change |
| Test scrape targets | curl http://localhost:9090/api/v1/targets | All targets health: "up" | Monitoring Lead | Daily |
| Query a sample metric | PromQL query in Prometheus UI | Returns time series data | DevOps Engineer | Weekly |
| Check alert state | curl http://localhost:9090/api/v1/alerts | Alerts in "firing" or "pending" state as expected | On-call Engineer (e.g., rotating) | Continuous |
| Review logs for errors | docker logs <container_name> --tail 50 | No critical errors | Developer (e.g., Lisa Nguyen) | Weekly |
| Backup configuration files | git commit or copy files | Configurations stored safely | DevOps Engineer | After changes |
| Review alert thresholds | Manual review of alert rules | Thresholds appropriate, no alert fatigue | Monitoring Lead | Monthly |
| Test notification flow | Send test alert to Alertmanager | Notification received in Slack/email | Monitoring Lead | Quarterly |
Run this checklist before and after any changes to the environment. Schedule periodic reviews (e.g., weekly) to ensure metrics are still relevant and alerts are not too noisy. The accountable owners should document any discrepancies and take corrective actions.
Conclusion
Monitoring Docker Compose profiles is essential for maintaining the health and performance of your applications. By following the steps outlined in this guide, you can set up a robust monitoring stack using Prometheus and Grafana, define meaningful alerts, and prepare for incident response. Start with a narrow, measurable pilot to validate your setup locally before scaling. Ensure you have a clear separation of profiles for monitoring to avoid interference with production services. With proper monitoring in place, you can detect issues early and keep your Docker Compose deployments running smoothly.
For next steps, consider expanding your monitoring to include log aggregation with Loki or adding more sophisticated alert routing with Alertmanager. Keep your monitoring configurations under version control and regularly review your dashboards to reflect changing application metrics. Remember to assign clear owners for monitoring tasks and review your setup periodically to ensure it continues to meet your needs.