使用宿主机IP
[root@localhost nginx]# ip addr show docker0
6: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:5f:26:5f:d7 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:5fff:fe26:5fd7/64 scope link
valid_lft forever preferred_lft forever
在Windows和macOS平台下并没有docker0
虚拟网卡,这时候可以使用host.docker.internal
这个特殊的DNS名称来解析宿主机IP
➜ ~ docker run --rm -it centos ping "host.docker.internal"
PING host.docker.internal (192.168.65.2) 56(84) bytes of data.
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=1 ttl=37 time=0.475 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=2 ttl=37 time=0.426 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=3 ttl=37 time=0.257 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=4 ttl=37 time=0.342 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=5 ttl=37 time=0.341 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=6 ttl=37 time=0.278 ms
使用host网络
docker run -d --name nginx --network host nginx
没有必要再使用-p 80:80 -p 443:443
这样的映射端口,是因为本身与宿主机共用了网络,容器中暴露端口等同于宿主机暴露端口。