Skip to content

您可以通过 host.docker.internal 域名从容器内访问宿主机,但需要显式配置 DNS 解析。以下是两种场景的具体用法:


1. 使用 docker run

docker run 命令中添加 --add-host 参数:

bash
docker run --add-host="host.docker.internal:host-gateway" -it your-image
  • host-gateway 是 Docker 内置的特殊值,会自动替换为宿主机在容器网络中的网关 IP(即宿主机地址)。
  • 添加后,容器内即可通过 host.docker.internal 访问宿主机。

示例:运行一个交互式容器并测试连通性

bash
docker run --add-host="host.docker.internal:host-gateway" -it alpine sh
# 在容器内执行
ping host.docker.internal

2. 使用 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 等)。

/src/technology/dateblog/2026/03/20260324-docker%E5%AE%B9%E5%99%A8%E4%BD%BF%E7%94%A8host-docker-internal%E5%9F%9F%E5%90%8D%E5%AE%B9%E5%99%A8%E5%86%85%E9%83%A8%E8%AE%BF%E9%97%AE%E5%AE%BF%E4%B8%BB%E6%9C%BA.html