How to Connect From a Docker Container to the Host

When we want to connect from the host system to an API inside a Docker container, we can map the port with the -p option and then access it through localhost. So far, so good. But what do we need to do if we want to make the connection in the reverse direction?

Thanks to the defaults of Docker, we can skip all the configuration ChatGPT suggests when we ask it for a solution. Instead, we change the URL we want to connect to from localhost (or 127.0.0.1) to this:

host.docker.internal 

That is all it takes.

No need to introduce docker-compose, no need to fiddle with the network configuration. Just replace localhost with host.docker.internal, keep the port at the value you use on the host system, and all works as expected. Sometimes things can be that simple.