Docker Compose部署Ocelot网关调用IdentityService失败求助
问题修复方案
1. 修正Ocelot路由的容器通信配置
容器内的localhost指向容器自身,无法访问另一个容器。需将Ocelot配置中的目标主机改为docker-compose定义的服务名identityservice,同时匹配容器内服务的实际监听端口:
{ "Routes": [ { "UpstreamPathTemplate": "/api/Identity/{Id}", "UpstreamHttpMethod": [ "GET" ], "DownstreamScheme": "http", // 开发环境先改用HTTP排查,后续再配置HTTPS "DownstreamHostAndPorts": [ { "Host": "identityservice", "Port": 3000 // 对应IdentityService容器内监听的端口 } ], "DownstreamPathTemplate": "/api/Identity/{Id}", "GatewayOptions": { "Timeout": 3000, "BaseUrl": "http://localhost:4592" } } ], "GlobalConfiguration": {} }
2. 统一容器内应用的监听端口
你的launchsettings.json配置应用本地监听5001/5002,但Dockerfile仅EXPOSE了3000/3001,导致容器内应用实际监听端口与Docker暴露端口不匹配。可通过以下方式修正:
方式一:在docker-compose.yml中添加环境变量
services: ocelotapigateway: container_name: api-gateway image: ${DOCKER_REGISTRY-}ocelotapigateway build: context: . dockerfile: OcelotApiGateway/Dockerfile ports: - 4592:3001 environment: - ASPNETCORE_URLS=http://+:3001 # 指定容器内应用监听3001端口 - ASPNETCORE_ENVIRONMENT=Development identityservice: container_name: identityservice image: ${DOCKER_REGISTRY-}identityservice build: context: . dockerfile: IdentityService/Dockerfile ports: - 4593:3000 environment: - ASPNETCORE_URLS=http://+:3000 # 指定容器内应用监听3000端口 - ASPNETCORE_ENVIRONMENT=Development
方式二:修改Dockerfile
在每个项目的Dockerfile末尾添加环境变量设置:
# IdentityService的Dockerfile ENV ASPNETCORE_URLS=http://+:3000 EXPOSE 3000 # OcelotApiGateway的Dockerfile ENV ASPNETCORE_URLS=http://+:3001 EXPOSE 3001
3. 容器内HTTPS配置(可选)
如果需要在容器内启用HTTPS,需将本地开发证书导入容器:
- 导出本地开发证书:
dotnet dev-certs https -ep ${HOME}/.aspnet/https/IdentityService.pfx -p 自定义密码 dotnet dev-certs https -ep ${HOME}/.aspnet/https/OcelotApiGateway.pfx -p 自定义密码 - 在docker-compose.yml中挂载证书并配置环境变量:
同时将Ocelot配置中的ocelotapigateway: # ...其他配置 environment: - ASPNETCORE_URLS=https://+:3001 - ASPNETCORE_Kestrel__Certificates__Default__Password=自定义密码 - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/OcelotApiGateway.pfx volumes: - ${HOME}/.aspnet/https:/https:ro identityservice: # ...其他配置 environment: - ASPNETCORE_URLS=https://+:3000 - ASPNETCORE_Kestrel__Certificates__Default__Password=自定义密码 - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/IdentityService.pfx volumes: - ${HOME}/.aspnet/https:/https:roDownstreamScheme改回https。
4. 验证连通性
部署后可进入网关容器测试容器间通信:
docker exec -it api-gateway curl http://identityservice:3000/api/Identity/641ee2820974a1c9b854c56e
如果能返回结果,再测试外部访问http://localhost:4592/api/Identity/641ee2820974a1c9b854c56e。
内容的提问来源于stack exchange,提问作者Jordi
相关产品推荐
相关产品推荐

