Connecting a FastAPI Docker Container to a Local PostgreSQL Database

In this article, we will explore the process of connecting a FastAPI project running inside a Docker container to a local PostgreSQL database. We will discuss the steps involved in setting up the environment variables, configuring the Docker Compose file, and resolving network connectivity issues to establish a successful connection.
Prerequisites
Before we begin, make sure you have the following:
- A FastAPI project set up with the necessary environment variables.
- Docker installed on your system.
- A local PostgreSQL database running on your machine.
Setting up the Docker Compose File
To start, let’s create a Docker Compose file that defines the configuration for our FastAPI container.
version: "3.9"
services:
panel_admin:
build:
context: ./
dockerfile: Dockerfile
env_file:
- .env
ports:
- "5000:5000"
deploy:
replicas: 1
resources:
limits:
cpus: '1'
memory: 512M
reservations:
cpus: '1'
memory: 512M
extra_hosts:
- "host.docker.internal:host-gateway"
By adding the extra_hosts
section, we enable the container to access the host machine using the host.docker.internal
hostname.
Resolving Network Connectivity Issues
When you try to connect to the database, you may see this error:no pg_hba.conf entry for host \”<your ip address>\”, user \”<database user>\”, database \”<database name>\”, no encryption
or this:Multiple exceptions: [Errno 111] Connection refused, [Errno 99] Cannot assign requested address
then you are in the right place, complete following this article.
To establish a successful connection between the Docker container and the local PostgreSQL database, we need to determine the IP address of our machine.
- Open your command prompt or terminal and run the following command:
ipconfigb
- Look for the IPv4 Address under your network adapter settings. Make a note of this address.
Configuring PostgreSQL Access
To allow the Docker container to connect to the PostgreSQL database, we need to make some adjustments in the database configuration.
- Open the
pg_hba.conf
file, typically located in the PostgreSQL installation directory. - Add the following line to the file:
host <db name> <db user> <IPv4 Address>/32 scram-sha-256
Replace <db name>
with the name of your database, <db user>
with the username associated with the database, and <IPv4 Address>
with the IP address of your machine
This configuration grants access to the specified database from the Docker container using the provided IPv4 address.
Conclusion
Congratulations! You have successfully connected your FastAPI Docker container to a local PostgreSQL database. By following the steps outlined in this article, you can ensure seamless communication between your containerized application and the database running on your machine.
Happy coding!