NGINX反向代理到docker应用程序

时间:2018-04-12 08:30:17

标签: docker nginx reverse-proxy devops

我目前正在学习设置nginx,但我已经遇到了问题。我的vps上运行了gitlab和nextcloud,并且可以通过正确的端口访问它们。因此,我使用简单的proxy_pass命令创建了一个nginx配置,但我总是透露502 Bad Gateway。 Nextcloud,Gitlab和NGINX是docker容器,NGINX已打开端口80。其余两个集装箱正在打开港口3000和3100。

  

/etc/nginx/conf.d/gitlab.domain.com.conf

upstream gitlab {
    server x.x.x.x:3000;
}
server {
    listen 80;
    server_name gitlab.domain.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://gitlab/;
     }
}
  

/var/logs/error.log

2018/04/12 08:10:41 [error] 7#7: *1 connect() failed (113: Host is unreachable) while connecting to upstream, client: xx.201.226.19, server: gitlab.domain.com, request: "GET / HTTP/1.1", upstream: "http://xxx.249.7.15:3000/", host: "gitlab.domain.com"
2018/04/12 08:10:42 [error] 7#7: *1 connect() failed (113: Host is unreachable) while connecting to upstream, client: xx.201.226.19, server: gitlab.domain.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://xxx.249.7.15:3000/favicon.ico", host: "gitlab.domain.com", referrer: "http://gitlab.domain.com/

我的配置有什么问题?

2 个答案:

答案 0 :(得分:1)

我认为你可以通过简单的配置方式逃脱。

也许是这样的:

http {
 ...
server {
listen 80;
charset utf-8;
...

location / {
  proxy_pass http://gitlab:3000;
}
}
}

我假设您使用docker的内部DNS来访问容器,例如gitlab指向gitlab容器内部IP。如果是这种情况,那么你可以打开一个容器并尝试从另一个容器ping gitlab容器。 例如,您可以从nginx容器中ping gitlab容器,如下所示:

 $ docker ps (use this to get the container id)

现在做:

$ docker exec -it <container_id_for_nginx_container> bash
# apt-get update -y
# apt-get install iputils-ping -y
# ping -c 2 gitlab

如果您无法ping通,则表示容器无法相互通信。你在使用docker-compose吗?如果你是那么我建议你看看“links”关键字,它用于链接应该能够相互通信的容器。例如,你可能会将gitlab容器链接到postgresql。

如果这有帮助,请告诉我。

答案 1 :(得分:0)

另一个利用您的Docker容器只是一个独立的控制组中的进程的优点的选项是将每个进程(容器)绑定到主机网络上的端口(而不是一个独立的网络组)。这会绕过Docker路由,因此请注意以下警告:端口可能不会在主机上重叠(与共享同一主机网络的任何正常进程没有什么不同。

您提到运行Nginx和Nextcloud(由于FastCGI支持,我假设您正在使用nextcloud fpm映像)。在这种情况下,我必须在Arch Linux机器上执行以下操作:

  1. /usr/share/webapps/nextcloud/var/www/html处绑定(绑定安装)到容器。
  2. 主机进程和容器进程的UID必须相同(在我的情况下,用户主机http和容器www-data的UID = 33)
  3. nginx.conf中的443服务器块必须将root设置为主机的nextcloud路径root /usr/share/webapps/nextcloud;
  4. 必须对通过FastCGI调用php-fpm的每个服务器块的FastCGI脚本路径进行调整,以引用Docker容器的Nextcloud基本路径fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;。换句话说,您不能像平常那样使用$document_root,因为它指向主机的nextcloud根路径。
  5. 可选:将config.php文件中的数据库和Redis路径调整为不使用localhost,而是使用主机的主机名。尽管localhost已绑定到主机的主网络,但似乎仍引用了容器的主机。