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?
2
Answers
Put container in Network "Host" to reach services via
localhost
or127.0.0.1
Or run bridged Network (per default) and access host via IP address:
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.