您可以通过 host.docker.internal 域名从容器内访问宿主机,但需要显式配置 DNS 解析。以下是两种场景的具体用法:
1. 使用 docker run
在 docker run 命令中添加 --add-host 参数:
bash
docker run --add-host="host.docker.internal:host-gateway" -it your-imagehost-gateway是 Docker 内置的特殊值,会自动替换为宿主机在容器网络中的网关 IP(即宿主机地址)。- 添加后,容器内即可通过
host.docker.internal访问宿主机。
示例:运行一个交互式容器并测试连通性
bash
docker run --add-host="host.docker.internal:host-gateway" -it alpine sh
# 在容器内执行
ping host.docker.internal2. 使用 docker-compose
在服务的 extra_hosts 字段中添加该条目:
yaml
services:
your-service:
image: your-image
extra_hosts:
- "host.docker.internal:host-gateway"完整示例(docker-compose.yml):
yaml
version: '3.8'
services:
app:
image: nginx
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "80:80"启动服务:
bash
docker-compose up说明
- 跨平台兼容:在 Linux 上使用原生 Docker Engine 时,
host.docker.internal默认不可用,必须通过上述方式添加。在 Docker Desktop(Mac/Windows)上该名称通常已内置,但显式添加也完全可行。 host-gateway的原理:Docker 会自动解析出宿主机在容器网络中的网关地址,并写入容器的/etc/hosts文件,效果等同于直接指定 IP。- 验证:进入容器后,可以执行
cat /etc/hosts查看是否已正确添加条目。
通过这种方式,无论您使用的是 docker run 还是 docker-compose,容器都能稳定地访问宿主机上运行的服务(如数据库、API 等)。