简体   繁体   English

Nginx 作为 docker 容器内的反向代理

[英]Nginx as a reverse proxy inside docker container

I'm trying to use nginx as a reverse proxy inside a container points to the different PHP application container.我正在尝试使用 nginx 作为容器内的反向代理,指向不同的 PHP 应用程序容器。 My PHP container gets requests from external port 8080 and forwards it to internal 80. I want my nginx to get listen to port 80 and forward the request to the PHP container on port 8080 but have issues redirecting the request.我的 PHP 容器从外部端口 8080 获取请求并将其转发到内部 80。我希望我的 nginx 监听端口 80 并将请求转发到端口 8080 上的 PHP 容器,但在重定向请求时遇到问题。

My nginx Dockerfile:我的 nginx Dockerfile:

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

My nginx 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;
    }
}

I've tried deploying it via docker-compose with the above yml file, but got the same error when CURL to the nginx.我已经尝试通过 docker-compose 使用上面的 yml 文件部署它,但是当 CURL 到 nginx 时遇到了同样的错误。 在此处输入图片说明

When CURL to HTTP://localhost:8080 (PHP application) and also to HTTP://localhost:80 (nginx) there's a log output from the docker-compose log.当 CURL 到 HTTP://localhost:8080(PHP 应用程序)和 HTTP://localhost:80(nginx)时,docker-compose 日志会输出一个日志。 在此处输入图片说明

But when CURL to nginx, I got the above error:但是当 CURL 到 nginx 时,我得到了上面的错误: 在此处输入图片说明

You have a misconfiguration here.您在这里配置错误。

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

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

Nginx can't reach of "localhost" of another container because it's a different container network. Nginx 无法访问另一个容器的“localhost”,因为它是不同的容器网络。

I suggest you create a docker network --network and place both containers to the network.我建议您创建一个--network network --network并将两个容器放置到网络中。 Then in Nginx config, you can refer php-app container by name.然后在 Nginx 配置中,您可以通过名称引用 php-app 容器。

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

Besides you can expose only the Nginx port and your backend will be safe.此外,您只能公开 Nginx 端口,您的后端将是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM