Home > OS >  can not connect with docker postgress sql container with psycopg2
can not connect with docker postgress sql container with psycopg2

Time:09-16

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 ?

CodePudding user response:

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-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.

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

CodePudding user response:

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.

  • Related