Instrumentação de Aplicativos Python em Containers com o Agent OpenTelemetry
Esta documentação explica como instrumentar aplicativos Python em contêiner usando o modelo zero-code, com o agente oficial do OpenTelemetry, adaptado para uso com o Elven Observability. A ideia é garantir coleta de traces (e opcionalmente métricas) sem alterações no código, apenas com ajustes no Dockerfile e nas variáveis de ambiente.
1. Instalação do Agent no Dockerfile
Adicione no Dockerfile
apenas os pacotes necessários de acordo com o seu framework. Veja abaixo os pacotes comuns e os específicos por framework:
Pacotes comuns (sempre instale):
RUN pip install \
opentelemetry-distro \
opentelemetry-exporter-otlp \
opentelemetry-instrumentation-requests
FastAPI:
RUN pip install opentelemetry-instrumentation-fastapi
Flask:
RUN pip install opentelemetry-instrumentation-flask
Django:
RUN pip install opentelemetry-instrumentation-django
❌ Não instale instrumentações desnecessárias. Ex: apps com Django não precisam de opentelemetry-instrumentation-fastapi.
Dockerfile de exemplo:
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV DJANGO_SETTINGS_MODULE=config.settings.base
WORKDIR /app
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
netcat-openbsd \
curl \
&& rm -rf /var/lib/apt/lists/*
# Install OpenTelemetry
RUN pip install opentelemetry-distro \
opentelemetry-exporter-otlp \
opentelemetry-instrumentation \
opentelemetry-instrumentation-django \
opentelemetry-instrumentation-requests
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["opentelemetry-instrument", "--", "gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000"]
2. Configuração das Variáveis de Ambiente
Defina as seguintes variáveis para ativar a instrumentação automática e enviar dados para o collector do Elven:
- name: OTEL_SERVICE_NAME
value: "python-app"
- name: OTEL_RESOURCE_ATTRIBUTES
value: "service=python-app,environment=production"
- name: OTEL_TRACES_EXPORTER
value: "otlp"
- name: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
value: "http://seu_collector_endpoint.com:4317/v1/traces"
- name: OTEL_METRICS_EXPORTER
value: "otlp"
- name: OTEL_EXPORTER_OTLP_METRICS_ENDPOINT
value: "http://seu_collector_endpoint.com:4317/v1/metrics"
Explicação:
OTEL_SERVICE_NAME
: nome do serviço exibido no Grafana/Tempo.OTEL_RESOURCE_ATTRIBUTES
: tags extras para enriquecer os traces.OTEL_EXPORTER_OTLP_*
: endpoints para envio dos dados.
3. Como iniciar o app com o agente (CMD)
Use o comando opentelemetry-instrument
como wrapper da aplicação. Veja abaixo exemplos por framework:
FastAPI (com Uvicorn)
CMD ["opentelemetry-instrument", "--", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Flask
CMD ["opentelemetry-instrument", "--", "python", "app.py"]
Django
CMD ["opentelemetry-instrument", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"]
Pode adaptar o comando conforme o seu entrypoint: gunicorn, uvicorn, waitress, etc.
4. Exemplos por Ambiente
Docker Compose
services:
api:
build: .
environment:
- OTEL_SERVICE_NAME=python-app
- OTEL_RESOURCE_ATTRIBUTES=service=python-app,environment=production
- OTEL_TRACES_EXPORTER=otlp
- OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://seu_collector_endpoint.com:4317/v1/traces
- OTEL_METRICS_EXPORTER=otlp
- OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://seu_collector_endpoint.com:4317/v1/metrics
Kubernetes
spec:
containers:
- name: python-app
image: python-app:latest
env:
- name: OTEL_SERVICE_NAME
value: "python-app"
- name: OTEL_RESOURCE_ATTRIBUTES
value: "service=python-app,environment=production"
- name: OTEL_TRACES_EXPORTER
value: "otlp"
- name: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
value: "http://seu_collector_endpoint.com:4317/v1/traces"
- name: OTEL_METRICS_EXPORTER
value: "otlp"
- name: OTEL_EXPORTER_OTLP_METRICS_ENDPOINT
value: "http://seu_collector_endpoint.com:4317/v1/metrics"
ECS (Fargate ou EC2)
"environment": [
{ "name": "OTEL_SERVICE_NAME", "value": "python-app" },
{ "name": "OTEL_RESOURCE_ATTRIBUTES", "value": "service=python-app,environment=production" },
{ "name": "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "value": "http://seu_collector_endpoint.com:4317/v1/traces" },
{ "name": "OTEL_TRACES_EXPORTER", "value": "otlp" },
{ "name": "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "value": "http://seu_collector_endpoint.com:4317/v1/metrics" },
{ "name": "OTEL_METRICS_EXPORTER", "value": "otlp" }
]
5. Troubleshooting
- Traces não aparecem: verifique se o endpoint está acessível e se o
CMD
usaopentelemetry-instrument
corretamente. - Timeout na aplicação: verifique se o collector está online e respondendo na porta 4318.
- Instrumentação duplicada: evite misturar instrumentação manual com o modo automático.
- Erro de dependência: cada framework precisa de sua instrumentação específica, revise o
pip install
.
6. Boas práticas
- Dê nomes significativos aos serviços (
OTEL_SERVICE_NAME=projeto-env-modulo
). - Separe ambientes (
environment=dev
,staging
,production
). - Não exponha credenciais nas variáveis de ambiente.
- Não use
OTEL_LOG_LEVEL=debug
em produção. - Teste localmente com
otel-cli
oucurl
para validar o collector.
7. Exemplo de .env
OTEL_SERVICE_NAME=python-app
OTEL_RESOURCE_ATTRIBUTES=service=python-app,environment=production
OTEL_TRACES_EXPORTER=otlp
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://seu_collector_endpoint.com:4317/v1/traces
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://seu_collector_endpoint.com:4317/v1/metrics
OTEL_METRICS_EXPORTER=otlp
Seu app Python agora está instrumentado com o Elven Observability, usando auto-instrumentação baseada em OpenTelemetry. Sem dor de cabeça, sem alterar o código-fonte. 🌟