我们正在docker swarm中运行grafana和nginx,并将url /foobar/代理到grafana的swarm实例。使用this guide,可以使用以下配置:

# nginx config
server {
    resolver 127.0.0.11 valid=30s;

    ...

    location /foobar/ {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://grafana:3000/;
        proxy_next_upstream error timeout http_502;
    }
}
# docker-compose
  grafana:
    image: ${REGISTRY}foo/grafana:${IMAGE_VERSION}
    networks:
      - foo
    volumes:
      - grafana:/var/lib/grafana
    environment:
      - GF_SERVER_ROOT_URL=%(protocol)s://%(domain)s:%(http_port)s/foobar/

但是,如果grafana服务不可用,这将导致nginx在启动时死亡。因此,为解决此问题,我们为proxy_pass指令使用了一个变量,并将其更改为:
server {
    resolver 127.0.0.11 valid=30s;

    ...

    location /foobar/ {
        set $grafana http://grafana:3000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass $grafana/;
        # proxy_pass http://grafana:3000/;
        proxy_next_upstream error timeout http_502;
    }

}

但是,这导致grafana以某种方式拒绝该请求。我可以验证grafana实际上正在接收请求(使用GF_SERVER_ROUTER_LOGGING=true),并且声称状态为200 ok,但是我在页面上唯一看到的是
If you're seeing this Grafana has failed to load its application files

1. This could be caused by your reverse proxy settings.

2. If you host grafana under subpath make sure your grafana.ini root_path setting includes subpath

3. If you have a local dev build make sure you build frontend using: npm run dev, npm run watch, or npm run build

4. Sometimes restarting grafana-server can help

为什么grafana会表现出这种现象,并且如何设置代理传递,以便nginx可以启动而无需尝试解析grafana URL(如果碰巧出现故障)?

最佳答案

使用变量时,完整URL是代理传递中的责任

    location /foobar/ {
        set $grafana http://grafana:3000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass $grafana$request_uri;
        # proxy_pass http://grafana:3000/;
        proxy_next_upstream error timeout http_502;
    }

如果基本路径不同,那么您将需要使用正则表达式来发送部分路径
    location ~ /foobar/(.*) {
        set $grafana http://grafana:3000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass $grafana/$1;
        proxy_next_upstream error timeout http_502;
    }

关于docker - Grafana不适用于Nginx proxy_pass变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56745127/

10-15 19:33