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 ?

TheTechGuy
  • 1,568
  • 4
  • 18
  • 45
  • Possible duplicate of [docker-compose: difference between network and link](https://stackoverflow.com/questions/41294305/docker-compose-difference-between-network-and-link) – awesoon Feb 10 '19 at 14:54
  • how ? would you please explain ? I read that but not getting it – TheTechGuy Feb 10 '19 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? – David Maze Feb 10 '19 at 15:15
  • I am working with Jupyter there – TheTechGuy Feb 10 '19 at 15:15
  • Sorry, this link is probably irrelevant here. I thought you are trying to access `db` inside `adminer`, is it correct? – awesoon Feb 10 '19 at 15:19
  • I am trying to access DB with python – TheTechGuy Feb 10 '19 at 15:20
  • @TheTechGuy Are you trying to connect to the database from your host machine? – Zak Feb 10 '19 at 15:55
  • yes, the same machine where the docker is running , I just need to insert data to the database. The database is running in Docker. and I have a Jupyter notebook with that I am trying to connect. While I am trying to connect i got the mentioned error. – TheTechGuy Feb 10 '19 at 16:01

3 Answers3

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

Zak
  • 1,005
  • 10
  • 22
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
Alphapico
  • 2,893
  • 2
  • 30
  • 29
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
AvkashChauhan
  • 20,495
  • 3
  • 34
  • 65