【问题标题】:Nginx status endpoint running inside Docker在 Docker 中运行的 Nginx 状态端点
【发布时间】:2018-05-11 15:30:32
【问题描述】:

我是 Nginx 的新手,我在 Docker 容器中运行它以服务于一个简单的网站。我想添加一个 /health 端点,它只返回状态 200 + 一些任意内容。

我从/etc/nginx/复制并调整了标准nginx.conf添加

server {
    location /health {
        return 200 "alive";
    }
}

http 块内的底部。但是当我运行 Docker 并尝试访问 localhost/health 时,我得到了 no such file or directory。访问localhost 的网站可以正常工作。

我还尝试复制其他代码块,例如,这个:https://gist.github.com/dhrrgn/8650077 但后来我得到conflicting server name "" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "" on 0.0.0.0:80, ignored

我是否将location 放置在nginx.conf 内的错误位置?我需要一些特殊的服务器配置吗?有什么问题?

【问题讨论】:

    标签: docker nginx endpoint


    【解决方案1】:

    问题出在我的 Nginx Docker 设置/配置上:我使用的是nginx:alpine,它的配置文件位于/etc/nginx/conf.d/。在那里,default.conf 定义了 Nginx 的默认配置。因此,我不得不删除 default.conf 并将我的配置复制到那里。在Dockerfile

    COPY nginx.conf /etc/nginx/conf.d/nginx.conf
    RUN rm /etc/nginx/conf.d/default.conf
    

    当然,我还得在nginx.conf中定义标准路由然后:

    server {
        location / {
            root /usr/share/nginx/html;
        }
    
        location /health {
            return 200 'alive';
            add_header Content-Type text/plain;
        }
    }
    

    【讨论】:

    • 所以我们不能在 default.conf 中添加 /health 吗?
    【解决方案2】:

    如果您想在一行中完成而不构建图像,您可以执行以下操作:

    #1 创建 Nginx.conf 文件

    nano /tmp/nginx-tester/nginx.conf
    

    并将以下内容放在那里:

    events {}
    
    http {
       server {
           location / {
               root /usr/share/nginx/html;
           }
       
           location /health {
               return 200 '{"status":"UP"}';
               add_header Content-Type application/json;
           }
       }
    }
    

    如果你看到了,它所做的就是提供一个带有 json 的 http 状态 200,说明状态是 UP

    #2 运行 NgInx 映像

    为了将它放在一行中,并且避免每次都重新创建图像,您可以像这样指定一个卷:

    docker run -it --rm -d -p 8077:80 --name nginx-tester -v /tmp/nginx-tester/nginx.conf:/etc/nginx/nginx.conf:ro nginx
    
    • -it:交互式进程(如 shell)
    • --rm: 容器退出时被移除
    • -p 8077:80: hostPort:containerPort
    • --name: 容器名称
    • -v: 绑定挂载卷(fileHost:fileContainer:ReadOnly)
    • nginx:将下载并运行的图像

    #3 测试一下

    您只需转到server:8077 就可以做到这一点(这是您在步骤#2 指定的端口)

    ~ > curl http://myserver:8077/health
    {"status":"UP"}
    

    ?这样你就可以更改配置文件,并且只需执行以下操作:

    docker restart nginx-tester
    

    您可以重新加载文件而无需重建图像。

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 2015-12-16
      • 2015-01-30
      • 2019-03-05
      • 2019-11-24
      • 2018-12-28
      • 1970-01-01
      • 2021-03-21
      • 2020-07-02
      相关资源
      最近更新 更多