Files
life-echo/docs/nginx-fix-guide.md
iammm0 3f9118c9cd docs: 新增网络和Nginx配置文档
- 新增network-config-guide.md网络配置指南
- 新增nginx-config-guide.md Nginx配置指南
- 新增nginx-fix-guide.md Nginx修复指南
- 新增nginx.conf示例配置
2026-01-28 13:01:06 +08:00

2.6 KiB
Raw Blame History

Nginx 配置修复指南

错误信息

host not found in upstream "life-echo-api-prod:8000"

问题原因

nginx 容器无法解析 life-echo-api-prod 主机名,说明:

  1. nginx 容器不在 life-echo-network 网络中
  2. 或者应该使用服务名而不是容器名

解决方案

方案 1使用主机端口最简单推荐

如果 nginx 在主机上运行,或通过主机端口访问,使用:

upstream lifecho_api_backend {
    server 127.0.0.1:8000;
}

优点:不需要配置网络,因为 docker-compose.yml 已经将容器的 8000 端口映射到主机的 8000 端口。

方案 2将 nginx 连接到同一网络

如果 nginx 在容器中运行,需要将其连接到 life-echo-network 网络:

步骤 1检查网络是否存在

docker network ls | grep life-echo-network

步骤 2将 nginx 容器连接到网络

# 如果 nginx 容器正在运行
docker network connect life-echo-network <nginx-container-name>

# 或者重启 nginx 容器时添加网络
docker run -d \
  --name nginx \
  --network life-echo-network \
  -v /path/to/nginx.conf:/etc/nginx/nginx.conf \
  nginx:latest

步骤 3使用服务名配置

upstream lifecho_api_backend {
    server api:8000;  # 使用服务名,不是容器名
}

方案 3在 docker-compose.yml 中添加 nginx 服务

如果希望统一管理,可以在 docker-compose.yml 中添加 nginx 服务:

services:
  # ... 其他服务 ...
  
  nginx:
    image: nginx:alpine
    container_name: life-echo-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - api
    networks:
      - life-echo-network
    restart: always

然后使用服务名:

upstream lifecho_api_backend {
    server api:8000;
}

验证修复

  1. 检查配置语法
nginx -t
  1. 重启 nginx
# 如果 nginx 在容器中
docker restart <nginx-container-name>

# 如果 nginx 在主机上
sudo systemctl restart nginx
# 或
sudo nginx -s reload
  1. 测试连接
# 测试健康检查
curl http://127.0.0.1:8000/health

# 测试通过 nginx
curl https://lifecho.worldsplats.com/health

当前推荐配置

根据错误信息,建议先使用方案 1(主机端口),因为:

  • 最简单,不需要配置网络
  • docker-compose.yml 已经映射了端口
  • 适用于大多数部署场景

如果方案 1 不工作nginx 在容器中且无法访问主机网络),再使用方案 2 或 3。