Docker容器无法访问主机localhost API,请求报错400求助
我正尝试在Docker容器内访问主机localhost上的API,查了不少指南但还是卡壳了,具体情况如下:
本地测试正常
在Windows命令提示符里用curl调用主机上的API完全正常:
curl http://localhost:57888/api/reference
对应的API代码:
[HttpGet()] public ActionResult CheckIfOnline() { // 断点能命中 return Ok(); }
Docker Compose配置
我在compose文件里添加了extra_hosts配置,以为这样容器就能访问主机:
container-api: container_name: container-api build: context: .. dockerfile: Dockerfile ports: - "3007:3001" env_file: - ./file.env extra_hosts: - "host.docker.internal:host-gateway"
连通性测试
容器启动后,ping host.docker.internal是能通的,返回IP为192.168.65.2:
ping host.docker.internal PING host.docker.internal (192.168.65.2) 56(84) bytes of data
查资料得知这是Docker的“魔法IP”,代表主机,但ipconfig里看不到这个IP,不过还是继续尝试调用API。
For Docker on Mac, there is a magic ip 192.168.65.2 in docker VM which represent host machine, or you can just use host.docker.internal inside docker VM will ok.
调用API报错
在容器bash里用curl调用API时,返回400错误:
# curl http://host.docker.internal:57888/api/reference <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <HTML><HEAD><TITLE>Bad Request</TITLE> <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> <BODY><h2>Bad Request - Invalid Hostname</h2> <hr><p>HTTP Error 400. The request hostname is invalid.</p> </BODY></HTML>
问题原因
这个400错误是因为你的ASP.NET(从代码判断)应用默认只绑定了localhost主机头,当从容器用host.docker.internal访问时,主机头不匹配,因此被拒绝。
解决方法
修改API的绑定与主机头限制
- 若为ASP.NET Core:在
Program.cs中修改应用绑定地址,并允许所有主机头:
同时在var builder = WebApplication.CreateBuilder(args); // 配置服务... var app = builder.Build(); // 配置中间件... app.Run("http://0.0.0.0:57888"); // 绑定到所有网卡地址appsettings.json中设置:"AllowedHosts": "*" - 若为传统ASP.NET Framework:修改项目
.vs\config\applicationhost.config中的站点绑定,允许任意主机头:<bindings> <binding protocol="http" bindingInformation="*:57888:*" /> </bindings>
- 若为ASP.NET Core:在
使用主机实际IP访问
找到主机在本地网络中的实际IP(比如通过ipconfig查看以太网/WLAN的IP,如192.168.1.100),在容器内用该IP调用API:curl http://192.168.1.100:57888/api/reference检查防火墙设置
确保主机防火墙允许57888端口的入站请求,尤其是来自Docker网络的请求。
内容的提问来源于stack exchange,提问作者user3428422

