【问题标题】:Nginx as a reverse proxy inside docker containerNginx 作为 docker 容器内的反向代理
【发布时间】:2020-11-08 19:36:42
【问题描述】:

我正在尝试使用 nginx 作为容器内的反向代理,指向不同的 PHP 应用程序容器。 我的 PHP 容器从外部端口 8080 获取请求并将其转发到内部 80。我希望我的 nginx 监听端口 80 并将请求转发到端口 8080 上的 PHP 容器,但在重定向请求时遇到问题。

我的 nginx Dockerfile:

FROM nginx:latest
COPY default.conf /etc/nginx/conf.d/default.conf

我的 nginx default.conf:

server {
  listen 80;
  error_page 497 http://$host:80$request_uri;
  client_max_body_size        32M;
  underscores_in_headers      on;

  location / {
    proxy_set_header    X-Forwarded-Host   $host; 
    proxy_set_header    X-Forwarded-Server $host; 
    proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for; 
    proxy_set_header    X-Forwarded-Proto  $scheme; 
    proxy_set_header    X-Real-IP          $remote_addr; 
    proxy_set_header    Host               $host;

    proxy_pass          http://php-container:8080;
    proxy_read_timeout  90;
    proxy_http_version  1.1;
    }
}

我尝试使用上述 yml 文件通过 docker-compose 部署它,但是当 CURL 到 nginx 时出现相同的错误。

当 CURL 到 HTTP://localhost:8080(PHP 应用程序)和 HTTP://localhost:80(nginx)时,docker-compose 日志会输出一个日志。

但是当 CURL 到 nginx 时,我得到了上述错误:

【问题讨论】:

    标签: docker nginx docker-compose nginx-reverse-proxy


    【解决方案1】:

    您的配置有误。

    nginx(主机:80 -> 容器:8080)

    php-app(主机:8080 -> 容器:80)

    Nginx 无法访问另一个容器的“localhost”,因为它是不同的容器网络。

    我建议你创建一个 docker 网络 --network 并将两个容器都放到网络中。然后在 Nginx 配置中,你可以按名称引用 php-app 容器。

        proxy_read_timeout      90;
        proxy_redirect          http://localhost:80/ http://php-container:8080/;
    

    除了你可以只暴露 Nginx 端口并且你的后端是安全的。

    【讨论】:

    • 我已经更新了 default.conf 以重定向到 php-container 而不是 localhost,并且还暴露了 nginx 的端口,但是当 CURL 到我的 localhost:80 时仍然出现同样的错误。
    猜你喜欢
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2018-03-20
    • 2017-11-13
    • 2020-08-11
    • 2015-01-05
    • 2020-09-10
    相关资源
    最近更新 更多