当通过Docker-compose运行时,Nginx无法find上游节点应用程序

我有一个超级简单的Node应用程序和一个Nginxconfiguration,它充当Node应用程序的反向代理。 如果我在本地运行Nginx(通过自制软件)和Node应用程序,一切正常。 如果我访问由端口8080上的Nginxconfiguration所定义的服务器,我将从端口3000上运行的节点应用程序获得输出。

我一直在试图将这个简单的设置转换为使用Docker,并写下了以下Docker-compose文件:

version: '3.0' services: web: build: . ports: - 3000:3000 nginx: build: context: . dockerfile: Dockerfile.nginx ports: - 8080:8080 

在运行docker-compose up构build图像,并在控制台中没有错误消息。 在访问localhost:3000我得到的节点应用程序的响应,但访问localhost:8080我得到一个Nginx的502错误页面,并在terminal中出现以下错误:

connect()失败(111:连接被拒绝)连接到上游时,客户端:172.18.0.1,服务器:localhost,请求:“GET / HTTP / 1.1”,上游:“ http://127.0.0.1:3000/ ”,主机:“localhost:8080”

我节点应用程序的Dockerfile如下所示:

 FROM node:carbon WORKDIR /app ADD . /app RUN npm install CMD ["node", "."] EXPOSE 3000 

和Dockerfile.nginx看起来像这样:

 FROM nginx COPY nginx.conf /etc/nginx/nginx.conf 

和nginx.conf看起来像这样:

 events { worker_connections 1024; } http { upstream node_app { server 127.0.0.1:3000; } server_tokens off; # Define the MIME types for files. include mime.types; default_type application/octet-stream; # Speed up file transfers by using sendfile() # TODO: Read up on this sendfile on; server { listen 8080; server_name localhost; location / { proxy_pass http://node_app; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; } } } 

在启动Docker后,我可以看到Nginx正在8080端口上运行(因为我看到了502页的Nginx页面),我可以看到节点应用程序正在运行(因为我可以在localhost:3000上访问它)。 我无法弄清楚为什么我从Nginx获得502。

我试过使用各种不同的东西,如使用links来链接容器和depends_on但似乎没有任何区别。 我也使用docker-compose up --build来确保每次我进行更改时都不会caching以前的版本。

编辑:东西,似乎使它的工作是将一个container_name属性添加到docker组成:

  web: container_name: nodeapp build: context: . dockerfile: Dockerfile.node ports: - 3000:3000 

然后在nginx.conf的上游node_appconfiguration中使用该容器名称:

  upstream node_app { server nodeapp:3000; } 

这对我没有意义?

问题是,在你的Nginxconfiguration中,你将Web服务的IP地址称为127.0.0.1,这是运行docker容器的主机的环回地址。 这可能取决于您的设置(操作系统,防火墙)或不可以。

正确的方法是使nginx服务取决于docker-compose.yml文件中的web服务,并更新Nginxconfiguration以通过名称( web )而不是IP地址引用Web服务。 在这里你可以find更多的信息有关docker撰写取决于能力。

更新的docker-compose.yml文件将是:

 version: '3.0' services: web: build: . nginx: build: context: . dockerfile: Dockerfile.nginx ports: - 8080:8080 depends_on: - web 

请注意,我已经停止公开web服务的端口。 可能是你需要保持监视Web服务,但不是必需的nginx服务。

通过对docker-compose.yml文件的更新,Nginx的configuration如下:

 events { worker_connections 1024; } http { upstream node_app { server web:3000; } server_tokens off; # Define the MIME types for files. include mime.types; default_type application/octet-stream; # Speed up file transfers by using sendfile() # TODO: Read up on this sendfile on; server { listen 8080; server_name localhost; location / { proxy_pass http://node_app; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; } } }