使用Docker的nginx:connect()失败(111:连接到上游时,连接被拒绝

whitzsjs  于 2023-06-05  发布在  Nginx
关注(0)|答案(1)|浏览(437)
  • 学习docker*

尝试使用nginx作为我的前端(react)和后端(GO)的代理。
docker-compose.yml

version: '3.8'
services:
  proxy:
    image: nginx:1.19-alpine
    container_name: proxy_server
    restart: unless-stopped
    ports:
      - 80:80
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - frontend
      - backend
    networks:
      - networkName
  frontend:
    image: front-end
    build: ./
    container_name: simple-front-end
    ports:
      - 3000:5000
    networks:
      - networkName
  backend:
    image: back-end
    build: ./back-end
    container_name: simple-back-end
    ports:
      - 7000:9000
    networks:
      - networkName
networks:
  networkName:

nginx.conf

events { worker_connections 1024; }

http {

  server {
    listen 80;

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

    location /api/ {
      proxy_set_header Host $host;
      proxy_pass http://backend:7000/api/;
    }
  }
}

控制台

proxy_server      | 192.168.192.1 - - [28/May/2023:13:25:11 +0000] "GET / HTTP/1.1" 502 560 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
proxy_server      | 2023/05/28 13:25:11 [error] 32#32: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.192.1, server: , request: "GET / HTTP/1.1", upstream: "http://192.168.192.2:3000/", host: "localhost"

我可以在浏览器中直接访问前端,地址为http://www.localhost:3000
无法通过位于http://www.localhost:80的代理访问它
我错过了什么?

xtupzzrd

xtupzzrd1#

阅读Networking in Compose后修复
Networked service-to-service communication uses the CONTAINER_PORT
更新nginx.conf

events { worker_connections 1024; }

http {

  server {
    listen 80;

    location / {
      proxy_pass http://frontend:5000;
    }

    # configure here where requests to http://localhost/api/...
    # are forwarded
    location /api/ {
      proxy_set_header Host $host;
      proxy_pass http://backend:9000/;
    }
  }
}

相关问题