Home > front end >  Why does localhost have to replaced with host.docker.internal when a container needs to connect to t
Why does localhost have to replaced with host.docker.internal when a container needs to connect to t

Time:12-03

I am currently learning the fundamentals of 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.

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.

Thanks in advance.

CodePudding user response:

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. They exist in their own cgroup for process isolation and network namespace for network isolation.

So, when some service in some container listens on "localhost:8080", other processes in that container can connect to that port. But processes in other containers cannot. They might, necessarially, have their own process listening on 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".

Its not a case of docker not understanding. This localhost redirection to the container is fundamental to the isolation that containerization brings.

  • Related