can not connect with docker postgress sql container with psycopg2

Question:

I am running a Postgres SQL database container with following command:

docker run  --name db -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -v pg

Of course I have changed the ‘localhost’ to ‘db’ since I am trying to connect with this container.
when I try to connect to the container database I get the following error:

psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known

I cant use here Docker compose in this context ( I know how to run it though ).
What else I need to add in my docker command so that I can connect from python ?

Answers:

If your Python program is running on the Docker host, then you don’t want to "of course" change localhost to db in your connection string, since (a) Docker doesn’t change your host DNS settings (b) you’re using -p to publish the service running on port 5432 to the host on port 5432.

You would only use the name db from another Docker container running in the same Docker network.

Answered By: AKX

Of course I have changed the ‘localhost’ to ‘db’ since I am trying to connect with this container.

No, you don’t, your dockerfile is exposing the port 5432 to the host machine as stated by the flag -p 5432:5432

So if, you are trying to connect to the docker from your host machine, yoi will use the host localhost

I think you are confusing between docker and docker networking when we have multiple docker trying to communicate with each other as is the case is with docker-compose.

In case of docker-compose, when you have multiple services running, they can communicate with each other using the docker containers name as the host. Similar if you have a network between docker containers, they can communicate with each other using the docker name as the host

So if it was docker-compose, with the docker running on one container, and your app in another, in that case you would replace localhost with db.

Hope that clarifies things

Answered By: Hassan Jalil
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.