skip to Main Content

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


  1. 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": ""
    
    Login or Signup to reply.
  2. –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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search