2

I have set up the following a Flask project but am having difficulties connected to the Postgresql database. I am sure it is not a port problem. The following is my flask project:

import os

from dotenv import load_dotenv
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from src.api.v1.core.health import HealthView

load_dotenv()

def create_app():
    app = Flask(__name__)

    app.config.from_object("src.settings")
    app.config.from_pyfile("settings.py", silent=True)

    HealthView.register(app)

    db = SQLAlchemy(app)
    db.create_all()

    return app

app = create_app()

if __name__ == "__main__":
    app.run(debug=True)

My .env file contains:

POSTGRES_HOSTNAME=localhost
POSTGRES_SERVICE_PORT=5432
POSTGRES_DB=database_name
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres

, my src/settings.py file:

# Postgres, SQLAlchemy
import os

db_uri = "{sql_protocol}://{user}:{pwd}@{host}:{port}/{db}".format(
    sql_protocol=os.environ.get("SQL_PROTOCOL", "postgresql"),
    host=os.environ.get("POSTGRES_HOSTNAME", "fill_me"),
    db=os.environ.get("POSTGRES_DB", "fill_me"),
    user=os.environ.get("POSTGRES_USER", "fill_me"),
    pwd=os.environ.get("POSTGRES_PASSWORD", "fill_me"),
    port=os.environ.get("POSTGRES_SERVICE_PORT", "5432"),
)

db_uri = db_uri.replace(" ", "")

SQLALCHEMY_DATABASE_URI = db_uri

, my docker-compose.yml file contains:

version: '3.9'

services:
  pythonapp:
    container_name: pythonapp
    image: pythonapp
    env_file:
      - ".env"
    build: .
    ports:
      - "80:80"
    depends_on:
      - db
    networks:
      - "backend"

  db:
    container_name: db
    image: "postgres:13.1-alpine"
    ports:
      - "5432:5432"
    env_file:
      - ".env"
    volumes:
      - postgres:/var/lib/postgresql/data
    networks:
      - "backend"


volumes:
  postgres:

networks:
  backend:
    name: "backend"
    driver: "bridge"

, my Dockerfile:

FROM python:3.6-slim-buster

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

EXPOSE 80

CMD ["flask", "run", "--host=0.0.0.0", "--port=80"]

, the requirements.txt file:

alembic==1.5.5
apispec==5.1.0
apispec-webframeworks==0.5.2
flasgger==0.9.5
flask
flask-classful==0.14.2
flask-restful
Flask-SQLAlchemy
marshmallow==3.13.0
psycopg2-binary
python-dotenv
pytz==2021.3
sqlalchemy-utils

I am getting the following error:

app.py:34: in <module>
    app = create_app()
app.py:25: in create_app
    db.create_all()
venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:1094: in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:1086: in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
venv/lib/python3.7/site-packages/sqlalchemy/sql/schema.py:4890: in create_all
    ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py:3146: in _run_ddl_visitor
    with self.begin() as conn:

. . .

venv/lib/python3.7/site-packages/sqlalchemy/engine/default.py:597: in connect
    return self.dbapi.connect(*cargs, **cparams)
venv/lib/python3.7/site-packages/psycopg2/__init__.py:122: in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
E   sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "*********" (127.0.0.1), port **** failed: Connection refused
E       Is the server running on that host and accepting TCP/IP connections?
E   connection to server at "*********" (127.0.0.1), port **** failed: Connection refused
E       Is the server running on that host and accepting TCP/IP connections?
E   connection to server at "*********" (::1), port **** failed: Cannot assign requested address
E       Is the server running on that host and accepting TCP/IP connections?
E   
E   (Background on this error at: https://sqlalche.me/e/14/e3q8)
=============================== warnings summary ===============================

What am I doing wrong? How can I get a more meaningful error, since the port number is not the problem and there are no other processes using that port?

  • I suggest you first troubleshoot the connection issues with command line `psql` client. Most likely the error is not related to Python code. – Mikko Ohtamaa May 23 '22 at 21:14
  • It's possible that the problem is that you are trying to connect to localhost from inside your Docker instance. This could be useful https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach – Gonzalo Odiard May 23 '22 at 21:25

0 Answers0