Grafana不适用于Nginx proxy_pass变量

时间:2019-06-24 23:36:22

标签: docker nginx grafana

我们正在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(如果碰巧掉了)?

1 个答案:

答案 0 :(得分:1)

使用变量时,完整的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;
    }