You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker容器化微服务:Ocelot网关Consul服务发现连接被拒

问题排查与解决方案

1. 修正Ocelot的Consul服务发现端口配置

错误提示connection refused(consul:8080),说明Ocelot尝试连接Consul的8080端口,但Consul默认运行在8500端口。检查Ocelot.json中的ServiceDiscoveryProvider节点,确保Port设置为8500:

"ServiceDiscoveryProvider": {
  "Host": "consul",
  "Port": 8500,
  "Type": "Consul"
}

2. 修正Consul服务注册的Address字段

Docker容器同一网络内,服务间通信依赖docker-compose定义的服务名作为DNS标识。你当前注册的api.usersettings.httpapi.host和api.gateway在Docker网络中可能无法被解析,需改为对应服务的docker-compose服务名:

  • 假设docker-compose.yml中UserSettingsService的服务名为usersettingsservice,则注册时的ServiceAddress应设为http://usersettingsservice:8080
  • 网关服务同理,注册地址改为docker-compose中网关的服务名+容器端口

以.NET服务注册代码为例:

services.AddConsulRegistration(options =>
{
    options.Address = new Uri("http://consul:8500");
    options.ServiceName = "UserSettingsService";
    options.ServiceAddress = new Uri("http://usersettingsservice:8080");
});

3. 验证Docker网络内的连通性

进入网关容器内部,测试服务与Consul的连通性:

# 进入网关容器
docker exec -it <apiGateway容器ID> bash

# 测试Consul服务查询是否正常
curl http://consul:8500/v1/catalog/service/UserSettingsService

# 测试能否访问UserSettingsService容器
curl http://usersettingsservice:8080/api/Home/testgateway

如果上述命令失败,说明网络或服务配置存在问题,需优先解决。

4. 确保Ocelot路由的ServiceName与Consul注册名完全匹配

Ocelot路由中的ServiceName必须和Consul中注册的服务名完全一致(大小写敏感):

"Routes": [
  {
    "UpstreamPathTemplate": "/UserService/testgateway",
    "UpstreamHttpMethod": ["GET"],
    "DownstreamPathTemplate": "/api/Home/testgateway",
    "ServiceName": "UserSettingsService",
    "LoadBalancerOptions": {
      "Type": "RoundRobin"
    }
  }
]

5. 确认容器端口使用正确

容器内部通信必须使用容器端口(8080),主机映射端口(8001、8002)仅用于外部访问,当前配置这部分是正确的,无需调整。


内容的提问来源于stack exchange,提问作者DeveloperAkash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:40:18