4

I am trying to use Postgresql with python. I have used the following docker compose the file.

version: '3.1'

services:

  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: admin_123
      POSTGRES_USER: admin

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

With the following code, I am trying to connect with the database.

conn = psycopg2.connect(
    database = "db_test",
    user ="admin",
    password = "admin_123",
    host = "db"
)

But I am getting this error.

OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known

What I am doing wrong ?

8
  • Possible duplicate of docker-compose: difference between network and link Commented Feb 10, 2019 at 14:54
  • how ? would you please explain ? I read that but not getting it Commented Feb 10, 2019 at 15:01
  • 1
    Where is your Python code running; on the host or in a container? If in a container, how did you start it? Commented Feb 10, 2019 at 15:15
  • I am working with Jupyter there Commented Feb 10, 2019 at 15:15
  • Sorry, this link is probably irrelevant here. I thought you are trying to access db inside adminer, is it correct? Commented Feb 10, 2019 at 15:19

3 Answers 3

7

You need to expose the BD port in the docker compose like this :

db:
image: postgres
restart: always
environment:
  POSTGRES_PASSWORD: admin_123
  POSTGRES_USER: admin
ports:
    - "5432:5432"

And then connect with localhost:5432

Sign up to request clarification or add additional context in comments.

Comments

1

Another possible scenario,

Check if ports have been used or not by other docker container. Use command:

$ docker container ls --format "table {{.ID}}\t{{.Names}}\t{{.Ports}}" -a

Comments

0

Here is my docker-compose.yml

$ cat docker-compose.yml

version: '3.1' # specify docker-compose version
services:
  dockerpgdb:
    image: postgres
    ports:
      - "5432:5432"
    restart: always
    environment:
      POSTGRES_PASSWORD: Password
      POSTGRES_DB: dockerpgdb
      POSTGRES_USER: abcUser
    volumes:
      - ./data:/var/lib/postgresql%

Now in PgAdmin4 you can setup a new server as below to test the connection:

host: localhost
port: 5432
maintenance database: postgres
username: abcUser
password: Password

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.