How to connect a FastAPI application and a PostgreSQL database on Digital Ocean

157 Views Asked by At

For some context, the FastAPI app is running on Ubuntu in a digital ocean droplet, and the database is a digital ocean managed database in a cluster.

I recently restored the database from backup after a mishap, and was able to recover lost data after querying with psql. Since both of them bore "Primary Only" I thought there might be conflicts, so I went ahead to destroy the original database.

However, seeing that the FastAPI app cannot connect with the database on digital ocean, i ran docker logs --tail 10 -f 2a7b5654b16b and found out that indeed there's no connection, see error message snippet below.

 File "/usr/local/lib/python3.9/site-packages/asyncpg/connect_utils.py", line 586, in _create_ssl_connection
    tr, pr = await loop.create_connection(
  File "uvloop/loop.pyx", line 1978, in create_connection
    ai_remote = f1.result()
socket.gaierror: [Errno -2] Name or service not known

On researching what the error message above means, I thought that it might need SSL certificate to encrypt connections between my client application and the database. I would have gone ahead to download and install the SSL certificate provided by Digital Ocean, but in database settings.py I saw that the environment variable for SSL is set to None; DB_SSL: Final = None, so I thought that means the application doesn't use database SSL after all.

The connection code looks like this;

    # DB settings
    # ------------------------
    DB_DRIVER: Final[str] = "postgresql+asyncpg"
    DB_HOST: Final[str] = os.environ.get("DB_HOST", "localhost")
    DB_PORT: Final[str] = os.environ.get("DB_PORT", "5432")
    DB_USER: Final[str] = os.environ.get("DB_USER", "postgres")
    DB_PASSWORD: Final[str] = os.environ.get("DB_PASSWORD", "")
    DB_DATABASE: Final[str] = os.environ.get("DB_DATABASE", "postgres")
    # If set to True, will print the executed SQL queries
    DB_ECHO: Final[bool] = False
    DB_SSL: Final = None
    DB_USE_CONNECTION_FOR_REQUEST: Final[bool] = True
    DB_RETRY_LIMIT: Final[int] = 1
    DB_RETRY_INTERVAL: Final[int] = 1

    DB_DSN: Final[
        str
    ] = f"{DB_DRIVER}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_DATABASE}"
db_engine = create_async_engine(
    Settings.DB_DSN,
    pool_size=10,
    max_overflow=10,
    echo=Settings.DB_ECHO,
    json_deserializer=orjson.loads,
    json_serializer=lambda j: orjson.dumps(j).decode("utf-8"),
    pool_pre_ping=True,
    pool_recycle=60,
    future=True,
)

I have never configured a database connection on digital ocean before so i don't know what to look out for, I'd appreciate any help, thank you.

0

There are 0 best solutions below