Problem entry · machine-readable · 编码代理与终端

Docker 容器内连不上宿主机服务(localhost 是容器自己,不是宿主机)

本页嵌入 #trove-entity JSON(本条目全量结构化数据);全库数据见 /agent/trove.json。

元数据

iddocker-host-access收录2026-08-29
问题域编码代理与终端主题分组容器与 WSL
适用工具docker · 外部工具

症状

宿主机上跑着服务(MySQL、Redis、本地 API…),容器里用 `localhost` 或 `127.0.0.1` 去连,连不上:

```

wget: can't connect to remote host: Connection refused

# 或 mysql: connect to 127.0.0.1 ... failed (Can't connect)

# 或 curl: (7) Failed to connect to localhost port 8123: Connection refused

```

特征:**服务在宿主机上明明能访问**(宿主 curl 127.0.0.1:端口 正常);容器网络模式是默认 bridge;换 `host.docker.internal` 在 Linux 上也不通(解析失败 `bad address`)。

原因

容器有独立的网络命名空间:**容器内的 localhost/127.0.0.1 指容器自己**,不是宿主机。默认 bridge 网络下,容器里没有你宿主机上那个服务,所以 Connection refused(不是防火墙,是地址根本指向容器自身)。`host.docker.internal` 这个主机名只有 Docker Desktop(Windows/macOS)自动注入,**原生 Linux 的 Docker 默认没有**,直接解析失败。

解法

三种方式(Linux 实测均可用,按场景选):

1. **宿主 IP(最通用)**:bridge 网络的默认网关就是宿主机,容器内访问 `http://172.17.0.1:<端口>`(docker0 的 IP,可用 `ip -4 addr show docker0` 查)。注意宿主服务要监听 `0.0.0.0` 而不是只监听 `127.0.0.1`,否则外部 IP 也连不上。

2. **host.docker.internal(推荐,配置文件友好)**:Linux 上用 `--add-host host.docker.internal:host-gateway` 把该主机名映射到宿主机(compose 里写 `extra_hosts:

- "host.docker.internal:host-gateway"`)。之后容器内 `host.docker.internal` 与 Docker Desktop 行为一致。macOS/Windows 的 Docker Desktop 无需配置自带。

3. **--network host(最简单,仅 Linux)**:`docker run --network host` 共享宿主机网络命名空间,容器内 localhost 就是宿主机,直接 `http://localhost:<端口>`。代价:不再有端口隔离,容器与宿主共用端口空间。

验证证据

- 本地实测(2026-08-29,WSL Ubuntu,docker 29.1.3,alpine:3.20;宿主机 python3 http.server :8123 监听 0.0.0.0):

- 复现:容器内 `wget http://localhost:8123/` → `Connection refused`(exit 1);

- 方法1:`wget http://172.17.0.1:8123/`(docker0 宿主侧 IP)→ 成功(exit 0);

- 方法2a:`wget http://host.docker.internal:8123/` → `bad address 'host.docker.internal:8123'`(Linux 默认无此主机名,exit 1);

- 方法2b:`--add-host host.docker.internal:host-gateway` 后同一 URL → 成功(exit 0);

- 方法3:`--network host` 后 `wget http://localhost:8123/` → 成功(exit 0)。

- 实测复现日志(2026-08-29)

来源与证据

素材来源:https://github.com/hankliu62/interview/issues/2102

验证证据:Evidence details kept locally (2026-08-29)