0

I am building a Flask application in Python. I'm using SQLAlchemy to connect to PostgreSQL.

I used this to successfully connect my SQLALchemy in the flask app to my postgresql.

engine = create_engine('postgresql://postgres:[mypassword]@localhost:5432/employee-manager-db')

I am get an error when I do docker-compose up. This is my docker-compose.yml

version: '3.8'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8000:8000
    volumes:
      - .:/app

    depends_on:
      - db

  db:
    image: postgres:14.5
    restart: always
    expose:
      - '5432'
    volumes:
      - .dbdata:/var/lib/postgresql
    ports:
      - '5432:5432'

I read the post Docker: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? and noted that I have to change my connection details in the config to connect to db:5432, but I am struggling to figure out how to do it. Where do I change the config?

Thank you so much for help.

NendoRiki
  • 51
  • 7
  • you need to change the line that you posted: `engine = create_engine......`. Replace `localhost` with `db` – Mihai Aug 30 '22 at 02:52

1 Answers1

1

The changes have to be made in your code not in the compose file, specifically

Change

engine = create_engine('postgresql://postgres:[mypassword]@localhost:5432/employee-manager-db')

To

engine = create_engine('postgresql://postgres:[mypassword]@db:5432/employee-manager-db')

The container is discoverable through its service name, in your case db.

In the first case you provided localhost instead, this would work if you didnt work with containers

But now your application lives in containers not in your host, so you need to change the address in order for the backend service to reach your db service

Tolis Gerodimos
  • 3,782
  • 2
  • 7
  • 14
  • Thank you so much! It solved the original problem. However, I now get "Is the server running on host "db" (172.20.0.2) and accepting TCP/IP connections on port 5432?", which is similar but "localhost" replaced with "db". Does this indicate that the server is not running on host "db"? Sorry I only studied software engineering for like a month and no idea what's happening – NendoRiki Aug 30 '22 at 04:04
  • For this it seems there is an issue with your db container. Create a new question with its log output and I would be glad to assist you further :) – Tolis Gerodimos Aug 30 '22 at 04:08