I’m currently containerizing my application, but I need it to connect to a PostgreSQL database that is running directly on my host machine’s localhost rather than inside a container. I’ve tried using 'localhost' and '127.0.0.1' inside my Docker settings, but the connection is always refused because it tries to look inside the container itself. Is there a universal DNS name or an IP configuration that allows a container to communicate back to the host OS seamlessly across Windows, Mac, and Linux?
3 answers
For developers on Docker Desktop (Windows and Mac), the easiest solution is using the special DNS name host.docker.internal. This automatically resolves to the internal IP address used by the host. If you are on Linux, it’s a bit different; you often need to add the flag --add-host=host.docker.internal:host-gateway to your docker run command or define it in your docker-compose.yml file. This maps the host's gateway IP to that specific hostname. This ensures that your application code remains portable across different development environments without hardcoding specific IP addresses that might change.
Does your host service's firewall allow connections from the Docker bridge network? I’ve noticed that even if you use the correct IP, sometimes the host OS blocks the incoming request because it sees it as coming from an external network interface rather than a local one.
If you are on Linux and don't want to use the host-gateway trick, you can run the container with --network="host". This makes the container share the host's networking namespace entirely.
I agree with Karen, but a word of caution: using --network="host" can be a security risk as it removes the isolation between the container and the host. It also only works on Linux, so if you're looking for a cross-platform solution for a team, Nancy's host.docker.internal suggestion is usually the more robust path to follow.
Steven, you are absolutely right to point that out. On Linux especially, ufw or iptables can drop packets from the docker0 interface by default. I’d suggest checking your service configuration too—for example, if it's a database, ensure it is listening on all interfaces (0.0.0.0) or specifically the Docker bridge IP, and not just locked to the host's loopback address. If the service only listens on 127.0.0.1 on the host, the container will never be able to reach it regardless of the Docker settings.