通过 docker-compose 将环境变量传递给 YAML

Pass Environment variable to YAML via docker-compose

我的prometheus.yml

global:
  scrape_interval:     15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ['localhost:9090']
  - job_name: golang 
    metrics_path: /prometheus
    static_configs:
      - targets:
        - localhost:9000

现在,我想动态传递主机名,而不是使用 localhost:9000 和 localhost:9090

我的docker-compose.yml使用这个prometheus.yml如下图:

prometheus:
    image: prom/prometheus:v2.24.0
    volumes:
      - ./prometheus/:/etc/prometheus/
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--web.console.libraries=/usr/share/prometheus/console_libraries'
      - '--web.console.templates=/usr/share/prometheus/consoles'
    network_mode: "host"
    ports:
      - 9090:9090
    restart: always

现在,我想传递这个主机地址:172.0.0.1 来自 docker-组合命令

我能做到:

Host=172.0.0.1 docker-compose up

但是,我怎样才能将这个值发送到 prometheus.yml?

提前致谢!

当您在 docker-compose 中传递此文件时,您可以使用相应的值在部署环境中轻松创建此配置文件。 test.yml

global:
  scrape_interval:     15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ['testserver:9090']
  - job_name: golang 
    metrics_path: /prometheus
    static_configs:
      - targets:
        - testserver:9000

docker-compose.yml

command:
      - '--config.file=/etc/prometheus/test.yml'

prod.yml

global:
  scrape_interval:     15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ['prodserver:9090']
  - job_name: golang 
    metrics_path: /prometheus
    static_configs:
      - targets:
        - prodserver:9000

docker-compose.yml

command:
      - '--config.file=/etc/prometheus/prod.yml'