0

I use the following docker-compose.yml file:

version: '3.8'

services:
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    expose:
      - 5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=testdb
volumes:
  postgres_data:

I bring it up with docker-compose up -d --build. Now when I try to access it from Python, say, with psycopg2 the following errors show up

>>> conn = psycopg2.connect(host="localhost", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

>>> conn = psycopg2.connect(host="db", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known

Could you help me to resolve that?

1
  • 1
    localhost is correct. Use ports: [5432:5432] rather than expose option. Commented Dec 21, 2021 at 18:28

3 Answers 3

1

The problem is that expose does not publish the ports to the host machine. They are only accessible to linked services.

You have to manually publish the ports:

docker-compose run -d -p 5432:5432 db
Sign up to request clarification or add additional context in comments.

1 Comment

You can also add this to docker-compose: ports: - "5432:5432"
0

You should remove expose option from your docker-compose.yml file and add ports option such as:

ports:
  -"5432:5432"

Then you can connect to database by host localhost from your application.

Comments

0

Instead of using expose us this instead:

ports:
  - "5432:5432"

This defines the port forwarding to the docker container

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.