Constank K0.0.4612577
I have PostgreSQL running on my host machine (not in Docker). My Node.js app runs inside a Docker container. When I set DATABASE_URL=postgresql://user:pass@localhost:5432/mydb, the container throws:
Error: connect ECONNREFUSED 127.0.0.1:5432
I have confirmed PostgreSQL is running on the host and I can connect from my terminal. What is the correct hostname to use from inside the container?
To connect to a PostgreSQL instance running on the host machine from a Docker container, you cannot use localhost as the hostname. This is because localhost refers to the container itself, not the host machine.
Instead, you can use the host.docker.internal hostname, which is a special hostname that Docker provides to access the host machine.
So, your DATABASE_URL should be:
DATABASE_URL=postgresql://user:pass@host.docker.internal:5432/mydb
This will allow your Node.js app running inside the Docker container to connect to the PostgreSQL instance running on the host machine.
Note: The host.docker.internal hostname is available on Docker Desktop for Windows and Mac, and on Docker Engine 20.10 and later for Linux. On earlier versions of Docker Engine for Linux, you can use the hostname of the host machine, or the IP address of the host machine, which can be obtained using docker run --rm -it --net=host --pid=host alpine /bin/sh -c "echo \"Host IP: $(ip route show default | awk '{print $3}')\"".
No contributions yet. Be the first to answer!
Connect your wallet to post a contribution.