0

I have a dotnet API that runs in a docker container.

From this API I would like to access a PostgreSQL database that is on the localhost where the container is executed. On Windows I ran this same application connecting to the localhost database using host.docker.internal but on linux it doesn't work.

My connection string is something like that:

"Server=host.docker.internal;Port=5432;Database=DbName;User Id=DbUser;Password=MyPassword;"

I tried to make the docker run by adding p --add-host=host.docker.internal:host-gateway, but it didn't work either.

I tested my PostgreSQL connection using pg_isready as below. And my connection is working:

pg_isready -d dbname -h myHost -p 5432 -U dbUserName

What am I missing?

George Wurthmann
  • 411
  • 2
  • 8
  • 20
  • Hi! `doesn't work` isn't descriptive enough. Do you get an error, timeout? Which ip is your db bound to? How are you connecting? Do you think this is the name resolution that isn't happening or connection being rejected? Have you tried connectivity by means other than connecting from the code, like pinging host.docker.internal from the container for example? – jabbson Dec 03 '21 at 03:14

2 Answers2

2

Put container in Network "Host" to reach services via localhost or 127.0.0.1

docker run --network="host"

Or run bridged Network (per default) and access host via IP address:

docker network inspect <name>
"IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1" <--- host IP
"Containers": {
            "048a..": {
                "Name": "container",
                "EndpointID": "81de..",
                "MacAddress": "02:42:..",
                "IPv4Address": "172.18.0.5/16", <-- container IP
                "IPv6Address": ""
araisch
  • 1,727
  • 4
  • 15
1

--add-host=host.docker.internal:host-gateway, but it didn't work either.

In this case, you can use docker run --add-host mypgserver:$(hostname -I | awk '{print $1}') ...

Your connection string:

"Server=mypgserver;Port=5432;Database=DbName;User Id=DbUser;Password=MyPassword;"

This method avoid using --network="host" which can cause port conflict if not careful.

gohm'c
  • 13,492
  • 1
  • 9
  • 16