# Nginx 配置修复指南 ## 错误信息 ``` host not found in upstream "life-echo-api-prod:8000" ``` ## 问题原因 nginx 容器无法解析 `life-echo-api-prod` 主机名,说明: 1. nginx 容器不在 `life-echo-network` 网络中 2. 或者应该使用服务名而不是容器名 ## 解决方案 ### 方案 1:使用主机端口(最简单,推荐) 如果 nginx 在主机上运行,或通过主机端口访问,使用: ```nginx upstream lifecho_api_backend { server 127.0.0.1:8000; } ``` **优点**:不需要配置网络,因为 `docker-compose.yml` 已经将容器的 8000 端口映射到主机的 8000 端口。 ### 方案 2:将 nginx 连接到同一网络 如果 nginx 在容器中运行,需要将其连接到 `life-echo-network` 网络: #### 步骤 1:检查网络是否存在 ```bash docker network ls | grep life-echo-network ``` #### 步骤 2:将 nginx 容器连接到网络 ```bash # 如果 nginx 容器正在运行 docker network connect life-echo-network # 或者重启 nginx 容器时添加网络 docker run -d \ --name nginx \ --network life-echo-network \ -v /path/to/nginx.conf:/etc/nginx/nginx.conf \ nginx:latest ``` #### 步骤 3:使用服务名配置 ```nginx upstream lifecho_api_backend { server api:8000; # 使用服务名,不是容器名 } ``` ### 方案 3:在 docker-compose.yml 中添加 nginx 服务 如果希望统一管理,可以在 `docker-compose.yml` 中添加 nginx 服务: ```yaml 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 ``` 然后使用服务名: ```nginx upstream lifecho_api_backend { server api:8000; } ``` ## 验证修复 1. **检查配置语法**: ```bash nginx -t ``` 2. **重启 nginx**: ```bash # 如果 nginx 在容器中 docker restart # 如果 nginx 在主机上 sudo systemctl restart nginx # 或 sudo nginx -s reload ``` 3. **测试连接**: ```bash # 测试健康检查 curl http://127.0.0.1:8000/health # 测试通过 nginx curl https://lifecho.worldsplats.com/health ``` ## 当前推荐配置 根据错误信息,建议先使用**方案 1**(主机端口),因为: - 最简单,不需要配置网络 - `docker-compose.yml` 已经映射了端口 - 适用于大多数部署场景 如果方案 1 不工作(nginx 在容器中且无法访问主机网络),再使用方案 2 或 3。