问题描述
当应用某个应用使用本地Docker容器部署,但是还需要访问本地服务时(如数据库),使用宿主机IP,127.0.0.1,localhost均无法访问,后2者好理解,都属于Docker容器的回环地址,前者:相当于Docker本身,对于Docker来说,容器与宿主机是用Docker虚拟机的网关来通讯,所以无法联接。
环境
Docker:Docker version 20.10.0, build 7287ab3
MacOS Catalina 10.15.7
官方给出的解决方案:
I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS namehost.docker.internal
which resolves to the internal IP address used by the host. This is for development purpose and does not work in a production environment outside of Docker Desktop.
意思就是,如果你想要从容器连接外部地址,在docker容器中,只需将db主机设置为host.docker.internal
这将被转发给运行docker容器的主机.
官方文档:https://docs.docker.com/desktop/networking/#per-container-ip-addressing-is-not-possible
简单的说就是数据库地址或者需要访问的本地服务的地址使用host.docker.internal
就可以了。