一、背景
需要在docker容器里访问宿主机提供的服务,例如容器里的应用需要访问宿主机提供的服务
二、解决方案
2.1、方案一
宿主机执行ifconfig,会查看到docker0 IP,可以使用此IP来访问宿主机
[root@localhost Nacos]# ifconfig | grep "docker0" -A20docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255ether 02:42:84:dc:e7:19 txqueuelen 0 (Ethernet)RX packets 0 bytes 0 (0.0 B)RX errors 0 dropped 0 overruns 0 frame 0TX packets 0 bytes 0 (0.0 B)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
2.2、方案二
docker 18.03 加入一个feature,在容器中可以通过host.docker.internal来访问主机
Use your internal IP address or connect to the special DNS name host.docker.internal which will resolve to the internal IP address used by the host.使用您的内部IP地址或连接到特殊的DNS名称host.docker.internal,它将解析到主机使用的内部IP地址
services:prometheus:image: prom/prometheus:latestcontainer_name: prometheusrestart: unless-stoppedvolumes:- ./config/prometheus.yml:/etc/prometheus/prometheus.yml- ./data/prometheus_data:/prometheuscommand:- --config.file=/etc/prometheus/prometheus.yml- --storage.tsdb.path=/prometheus- --web.console.libraries=/etc/prometheus/console_libraries- --web.console.templates=/etc/prometheus/consoles- --web.enable-lifecycleextra_hosts: # 将内容添加到容器的/etc/hosts中- host.docker.internal:host-gatewayports:- 9090:9090networks:middleware-network:aliases:- prometheus
注意如果版本低于20.10.0,extra_hosts需要配置为:”host.docker.internal:172.101.0.1”(172.101.0.1根据具体来填写),否则为报错提示:”invalid IP address in add-host: “host-gateway”
services:app:extra_hosts:- "host.docker.internal:172.101.0.1"
