朕喜技术(ZhenxiJS)
2026.08.22
1 分钟阅读
Docker 容器里访问宿主机服务 localhost 不通怎么连
关键词:Docker、docker-compose、容器访问宿主机、host.docker.internal、bridge 网络、容器网络、host-gateway
一、问题背景
在宿主机上运行了一个服务(本地 API / 数据库 / dev server),监听 0.0.0.0:8080。
在 Docker 容器里写 http://localhost:8080 去访问,结果 Connection refused / 连不上。
这是极高频的容器网络坑:容器里的 localhost 指向容器自己,不是宿主机。
二、复现步骤
cd scenario/2026-08-22/
docker compose up -d --build
docker compose exec app bash
# 容器内:
curl -s http://localhost:8080 # ❌ 失败
三、根本原因
Docker 容器有独立网络命名空间,回环接口(127.0.0.1)属于容器自己。 宿主机监听的端口在宿主机的网络命名空间里,容器内通过 localhost 自然访问不到。
四、解决办法
方案 A(推荐):host.docker.internal + extra_hosts: host-gateway
Linux 版 Docker 需要手动映射:
services:
app:
extra_hosts:
- "host.docker.internal:host-gateway"
脚本里用 http://host.docker.internal:8080 即可。host-gateway 自动解析为宿主机 bridge 网关 IP,可移植。
方案 B:宿主机网关 IP
GATEWAY=$(ip route | awk '/default/{print $3}')
curl -s "http://${GATEWAY}:8080"
方案 C:network_mode: host(谨慎,破坏隔离)
五、验证
docker compose exec app bash /workspace/scenario/2026-08-22/container_client.sh
# 输出 ✅ 成功:容器已能访问宿主机服务!
六、经验与避坑
- 容器里 localhost ≠ 宿主机 localhost(除非 host 网络)。
- Linux 上没有内置 host.docker.internal,需
extra_hosts: host-gateway。 host-gateway自动解析网关 IP,比手写 IP 更健壮。- 需要 Docker 20.10+ 才支持 host-gateway 语法。
