Home > Back-end >  Specifying ports inside docker-compose.yml for using postgresql
Specifying ports inside docker-compose.yml for using postgresql

Time:08-30

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.

CodePudding user response:

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

  • Related