This document explains how to set up monitoring for the Django application in the ft_transcendence project.
- Setting up django-prometheus
- Setting up Prometheus and Grafana with Docker Compose
- Adding Grafana Dashboards
django-prometheus is a Python library that exports monitoring metrics from Django applications to Prometheus.
pip install django-prometheus
- Add the following to
settings.py
:
INSTALLED_APPS = [
...
"django_prometheus",
]
MIDDLEWARE = (
["django_prometheus.middleware.PrometheusBeforeMiddleware"]
+ MIDDLEWARE
+ ["django_prometheus.middleware.PrometheusAfterMiddleware"]
)
- Add the following to
urls.py
:
urlpatterns = [
...
path("prometheus/", include("django_prometheus.urls")),
]
This will make metrics available at the /prometheus/metrics
endpoint.
Create a docker-compose.monitoring.yml
file with the following content:
version: "3.8"
networks:
monitoring:
driver: bridge
volumes:
prometheus_data: {}
grafana-data: {}
services:
prometheus:
image: prom/prometheus:latest
container_name: prometheus
restart: unless-stopped
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- "--config.file=/etc/prometheus/prometheus.yml"
- "--storage.tsdb.path=/prometheus"
- "--web.console.libraries=/etc/prometheus/console_libraries"
- "--web.console.templates=/etc/prometheus/consoles"
- "--web.enable-lifecycle"
ports:
- 9090:9090
networks:
- monitoring
grafana:
image: grafana/grafana-oss:latest
container_name: grafana
ports:
- "3000:3000"
volumes:
- grafana-data:/var/lib/grafana
restart: unless-stopped
networks:
- monitoring
Create a prometheus.yml
file with the following content:
global:
scrape_interval: 15s
scrape_configs:
- job_name: "django_app"
metrics_path: "/prometheus/metrics"
static_configs:
- targets: ["host.docker.internal:8080"]
Note: Adjust the targets
value to match the actual host and port of your Django application.
docker-compose -f docker-compose.monitoring.yml up --build
This will make the following services available:
- Grafana:
http://localhost:3000
- Prometheus:
http://localhost:9090
- Log in to Grafana (default credentials: admin/admin)
- Go to "Configuration" → "Data sources" in the left menu
- Click "Add data source"
- Select Prometheus
- Set the following:
- Name: Prometheus
- URL:
http://prometheus:9090
- Click "Save & Test"
- Go to "Create" → "Import" in the left menu
- Enter Django Prometheus dashboard URL in "Import via grafana.com".
- Click "Load"
- Select Prometheus as the data source
- Click "Import"
You should now have a dashboard displaying metrics from your Django application.
- If metrics are not showing up, ensure that your Django application is running correctly and that the Prometheus configuration is correct.
- If Grafana fails to connect to the data source, check your network settings and ensure that the Prometheus container is reachable from the Grafana container.