在Docker中使用Nginx反向代理

时间:2018-05-29 12:07:10

标签: docker nginx docker-compose

我正在尝试开发一个部署在Nginx上的分布式Angular应用程序,它应该连接到后端服务。

搬运工-compose.yml:

version: '3'
services: 
  backend_service_1:
    build:
      context: ./app
      dockerfile: Dockerfile
    ports:
      - "3001:5000"
    networks: 
      - my-network

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile.3      
    ports:
      - "3000:80"
    networks: 
      - my-network
    links:
      - backend_service_1

networks: 
  my-network:

nginx.conf:

upstream backend {
  server backend_service_1:3001;
}

server {
  listen 80;
  server_name localhost;

  location / {
    root /usr/share/nginx/html/ki-poc;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }

  location /backend {
    proxy_pass http://backend/;
    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
  }
}

我可以在localhost:3000上访问该应用。我还可以使用浏览器从localhost:3001的后端服务获得响应。但是,当我尝试使用localhost:3000/backend上的代理从后端服务获取响应时,我收到以下错误消息: [error] 5#5: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /backend HTTP/1.1", upstream: "http://172.20.0.2:3001/", host: "localhost:3000"

你能告诉我,为什么对链接后端容器的请求被拒绝了?

1 个答案:

答案 0 :(得分:1)

你应该在nignx配置中使用容器的端口,而不是主机的端口。

upstream backend {
    server backend_service_1:5000;
}