[英]Why does localhost have to replaced with host.docker.internal when a container needs to connect to the host machine?
I am currently learning the fundamentals of docker.我目前正在学习 docker 的基础知识。 I have learnt that when a container needs to connect to the host machine (let's say I have a local mysql database), instead of using localhost
as the domain, it has to use host.docker.internal
as the domain.我了解到,当容器需要连接到主机时(假设我有一个本地 mysql 数据库),而不是使用localhost
作为域,它必须使用host.docker.internal
作为域。
So instead of something like this:所以不是这样的:
createConnection(
host: "localhost",
...
)
I would do this:我会这样做:
createConnection(
host: "host.docker.internal",
...
)
I think I understand why this is the case, but I just wanted to clarify why docker doesn't understand what localhost
means, and why it has to be replaced with host.docker.internal
.我想我明白为什么会这样,但我只是想澄清为什么 docker 不明白localhost
的含义,以及为什么必须将其替换为host.docker.internal
。
Thanks in advance.提前致谢。
docker understands perfectly well what "localhost" means: When you create a container you are creating an isolated set of processes that can see only each other. docker 非常了解“本地主机”的含义:当您创建容器时,您正在创建一组相互隔离的进程,这些进程只能彼此看到。 They exist in their own cgroup for process isolation and network namespace for network isolation.它们存在于自己的 cgroup 中用于进程隔离和网络命名空间用于网络隔离。
So, when some service in some container listens on "localhost:8080", other processes in that container can connect to that port.因此,当某个容器中的某些服务侦听“localhost:8080”时,该容器中的其他进程可以连接到该端口。 But processes in other containers cannot.但是其他容器中的进程不能。 They might, necessarially, have their own process listening on localhost:8080.他们可能有自己的进程在 localhost:8080 上监听。
In this environment, where each container has its own ip address on a virtual network, and needs to be bridged to the hosts network, localhost
will of course mean "the container", not "the containers host OS".在这种环境中,每个容器在虚拟网络上都有自己的 ip 地址,并且需要桥接到主机网络, localhost
当然意味着“容器”,而不是“容器主机操作系统”。
Its not a case of docker not understanding.它不是 docker 不理解的情况。 This localhost redirection to the container is fundamental to the isolation that containerization brings.这种 localhost 重定向到容器是容器化带来的隔离的基础。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.