Nginx反向代理报错host not found in upstream问题求助
问题排查:Nginx反向代理无法解析上游服务
space-api 问题现象
容器化部署Angular前端、Node.js后端、MongoDB数据库及Nginx反向代理后,前端可正常访问,但Nginx日志抛出错误:
[emerg] 1#1: host not found in upstream "space-api" in /etc/nginx/nginx.conf:23
核心原因
Docker Compose中,reverse_proxy和space-frontend默认加入了Compose自动创建的默认网络,而space-api与database加入了自定义外部网络node-network,跨网络的容器无法通过服务名进行DNS解析,导致Nginx找不到space-api服务。
修复步骤
1. 统一所有服务的网络归属
将reverse_proxy和space-frontend也加入node-network,确保需要通信的容器处于同一网络环境。
2. 清理冗余配置
- 移除
space-api中的links配置(Docker Compose 3.x版本推荐用网络通信代替links) - 移除
space-api中的hostname配置(Compose默认会将服务名作为容器的DNS别名,无需额外设置)
修改后的Docker Compose配置
version: "3.8" services: reverse_proxy: image: nginx:1.17.10 container_name: reverse_proxy depends_on: - space-frontend - space-api - database volumes: - ./reverse_proxy/nginx.conf:/etc/nginx/nginx.conf ports: - 80:80 networks: - node-network # 加入统一网络 space-frontend: container_name: space-frontend image: space-frontend build: context: ./space-frontend ports: - 4000:80 networks: - node-network # 加入统一网络 space-api: container_name: space-api image: space-api build: context: ./space-api ports: - 3000:3000 environment: MONGO_INITDB_DATABASE: spaceLocator MONGODB_URI: mongodb://db:27017 depends_on: - database volumes: - ./db-data/mongo/:/data/database networks: - node-network database: container_name: db image: mongo restart: on-failure ports: - 27017:27017 volumes: - ./mongodb:/data/database networks: - node-network volumes: dbdata6: networks: node-network: external: true driver: bridge
额外优化建议
- 添加健康检查,确保数据库和API服务就绪后再启动反向代理,避免启动顺序问题导致的临时解析失败:
# 在database服务中添加 healthcheck: test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"] interval: 10s timeout: 5s retries: 5 # 在space-api服务中添加 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 10s timeout: 5s retries: 5 # 修改reverse_proxy的depends_on depends_on: space-frontend: condition: service_started space-api: condition: service_healthy database: condition: service_healthy - 确保外部网络
node-network已存在,若不存在可执行命令创建:docker network create node-network
内容的提问来源于stack exchange,提问作者M Safdar Ali Khan
相关产品推荐
相关产品推荐

