prometheus

prometheus

  • Expondo as métricas do nginx pro prometheus

    Esses dias eu peguei um problema no servidor web, nginx. Não nele especificamente. Mas um usuário estava reclamando que estava super lento pra carregar as páginas.

    A questão então é como ver como e quanto está o nginx. Infelizmente a versão open source não fornece muita coisa. Só uma versão texto de estatísticas.

    Não é grande coisa mas pelo menos já é ALGUMA COISA.

    Agora como monitorar isso no Grafana?

    A resposta são open metrics. E isso não tem.

    Não tinha.

    Fiz um programa em Go que converte essas estatísticas em open metrics e expõe na porta 9090 no endpoint /metrics.

    Pra ter isso funcionando, é preciso primeiro subir a configuração de estatísticas no nginx.

    
    server {
        listen 127.0.0.1:8080;
        location /api {
            stub_status;
            allow 127.0.0.1;
            deny all;
        }
    }  
    
    

    Eu salvei no arquivo statistics.conf e coloquei em /etc/nginx/conf.d. E bastou um reload pra ter funcionado.

      
    ❯ curl localhost:8080/api
    Active connections: 2 
    server accepts handled requests
     21 21 322 
    Reading: 0 Writing: 1 Waiting: 1   
     
    

    Agora é rodar o programa e apontar pra esse endpoint.

      
    ❯ ./nginx-openmetrics/nginx-openmetrics --service=http://localhost:8080/api
    [2025-08-22T14:11:45] (INFO): 🚚 fetching data from:http://localhost:8080/api
    [2025-08-22T14:11:45] (INFO): 🎬 starting service at port:9090    
     
    

    E a porta fica exposta pras métricas serem coletadas pelo prometheus ou grafana alloy. Ou qualquer outro programa que faça scrape de dados no padrão open metrics.

      
    ❯ curl localhost:9090/metrics
    # HELP active_connections The number of active connections
    # TYPE active_connections gauge
    active_connections 1
    # HELP reading_connections The number of active reading connections
    # TYPE reading_connections gauge
    reading_connections 0
    # HELP server_accepts_total The total number of server accepted connections
    # TYPE server_accepts_total counter
    server_accepts_total 22
    # HELP server_handled_total The total number of server handled connections
    # TYPE server_handled_total counter
    server_handled_total 22
    # HELP server_requests_total The total number of server requests
    # TYPE server_requests_total counter
    server_requests_total 333
    # HELP waiting_connections The number of waiting connections
    # TYPE waiting_connections gauge
    waiting_connections 0
    # HELP writing_connections The number of active writing connections
    # TYPE writing_connections gauge
    writing_connections 1  
     
    

    E fica exposto em todas as interfaces.

      
    ❯ netstat -nat | grep 9090 | grep -i listen
    tcp6       0      0 :::9090                 :::*                    LISTEN         
     
    

    O programa faz o update dos dados a cada 15 segundos. Pra não sobrecarregar.

    E ainda falta dar uma melhorada com a entrada como serviço do systemd. Devo fazer isso hoje.

    Próximo passo será gerar um pacote debian dele pra instalar fácil.

    Update: Fri Aug 22 04:23:45 PM CEST 2025
    Tá lá o arquivo pro systemd. E está funcionando no sistema que estou testando.

      
    root@server:/# systemctl status nginx-openmetrics.service 
    ● nginx-openmetrics.service - nginx open metrics service
         Loaded: loaded (/etc/systemd/system/nginx-openmetrics.service; enabled; vendor preset: enabled)
         Active: active (running) since Fri 2025-08-22 14:08:17 UTC; 16min ago
       Main PID: 314061 (nginx-openmetri)
          Tasks: 7 (limit: 19076)
         Memory: 4.0M
            CPU: 47ms
         CGroup: /system.slice/nginx-openmetrics.service
                 └─314061 /usr/sbin/nginx-openmetrics --service=http://localhost:8080/api
    
    Aug 22 14:08:17 internal systemd[1]: Started nginx open metrics service.
    Aug 22 14:08:17 internal nginx-openmetrics[314061]: [2025-08-22T14:08:17.78433] (INFO): nginx-open-metrics-service (1.0-9)
    Aug 22 14:08:17 internal nginx-openmetrics[314061]: [2025-08-22T14:08:17.78441] (INFO): 🚚 fetching data from:http://localhost:8080/api
    Aug 22 14:08:17 internal nginx-openmetrics[314061]: [2025-08-22T14:08:17.78442] (INFO): 🎬 starting service at port:9090    
     
    
  • Habilitando Prometheus pra coletar as métricas do GoToSo

    Numa discussão no fediverso falamos sobre habilitar as métricas do GoToSo, também conhecido como GoToSocial. Fiz algumas mudanças e consegui expor essas métricas.

    O compose.yaml do GoToSo:

      
    services:
      gotosocial:
        image: docker.io/superseriousbusiness/gotosocial:latest
        container_name: gotosocial
        user: 1000:1000
        networks:
          - gotosocial
        environment:
          GTS_HOST: bolha.linux-br.org
          GTS_DB_TYPE: postgres
          GTS_CONFIG_PATH: /gotosocial/config.yaml
          [...]
          OTEL_METRICS_PRODUCERS: prometheus
          OTEL_METRICS_EXPORTER: prometheus
          OTEL_EXPORTER_PROMETHEUS_HOST: 0.0.0.0
          OTEL_EXPORTER_PROMETHEUS_PORT: 9090
          [...]
        ports:
          - "8080:8080"
          - "9090:9090"
        [...]
     
    

    A config.yaml também do GoToSo:

      
    [...]
    media-emoji-local-max-size: 250KiB
    media-emoji-remote-max-size: 250KiB
    advanced-rate-limit-requests: 0
    metrics-enabled: true
     
    

    Uma vez que isso estava habilitado e o container reiniciado, foi só verificar a porta 9090.

      
    ❯ curl -s localhost:9090/metrics | head -10
    # HELP go_config_gogc_percent Heap size target percentage configured by the user, otherwise 100.
    # TYPE go_config_gogc_percent gauge
    go_config_gogc_percent{otel_scope_name="go.opentelemetry.io/contrib/instrumentation/runtime",otel_scope_schema_url="",otel_scope_version="0.63.0"} 100
    # HELP go_goroutine_count Count of live goroutines.
    # TYPE go_goroutine_count gauge
    go_goroutine_count{otel_scope_name="go.opentelemetry.io/contrib/instrumentation/runtime",otel_scope_schema_url="",otel_scope_version="0.63.0"} 167
    # HELP go_memory_allocated_bytes_total Memory allocated to the heap by the application.
    # TYPE go_memory_allocated_bytes_total counter
    go_memory_allocated_bytes_total{otel_scope_name="go.opentelemetry.io/contrib/instrumentation/runtime",otel_scope_schema_url="",otel_scope_version="0.63.0"} 1.6433066284e+11
    # HELP go_memory_allocations_total Count of allocations to the heap by the application.    
     
    

    Em seguida subi um container, também com podman, pra coletar esses dados. Junto com um prometheus-exporter pra coletar dados da máquina.

    compose.yaml:

      
    services:
      prometheus:
        image: quay.io/prometheus/prometheus
        container_name: prometheus
        environment:
          TZ: Europe/Stockholm
        ports:
          - "9000:9090"
        volumes:
          - data:/prometheus
          - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
        restart: unless-stopped
        extra_hosts:
          - localserver:192.168.1.2
            
    volumes:
      data:
     
    

    prometheus.yml:

      
    global:
      scrape_interval: 15s
      evaluation_interval: 15s
    
    scrape_configs:
      - job_name: "prometheus"
        static_configs:
          - targets: 
            - "localhost:9090"
            labels:
              app: "prometheus"
    
      - job_name: "mimir"
        static_configs:
          - targets:
            - "localserver:9100"
            labels:
              app: "mimir"
    
      - job_name: "gotoso"
        static_configs:
          - targets:
            - "localserver:9090"
            labels:
              app: "gotoso"    
     
    

    Isso já faz subir e você pode olhar no target health.

    Daí é deixar o Prometheus coletar os dados e depois olhar os gráficos.

    Ninguém me segurou, mas também não instalei o Grafana.

    Por enquanto...

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.