PostgreSQL is one of the most powerful and popular relational databases, while Docker and Docker Compose simplify the creation of containerized development environments. In this article, we will explore how to configure and use PostgreSQL in a Docker container and interact with it using Python.
Creating the docker-compose.yml
File
Let's start by creating a docker-compose.yml
file to define the PostgreSQL container:
version: '3.8'
services:
db:
image: postgres:15
container_name: postgres_container
environment:
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
POSTGRES_DB: mydatabase
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Starting the Service
Start PostgreSQL with the following command:
docker compose up -d
This will create a container with PostgreSQL listening on port 5432
.
Installing Python Libraries
Install the psycopg2
library to interact with PostgreSQL from Python:
pip install psycopg2
Python Script to Connect to PostgreSQL
Create a Python script to connect to and interact with the database:
import psycopg2
def connect_to_db():
try:
connection = psycopg2.connect(
database="mydatabase",
user="myuser",
password="mypassword",
host="localhost",
port="5432"
)
cursor = connection.cursor()
cursor.execute("SELECT version();")
db_version = cursor.fetchone()
print("Connection established. Database version:", db_version)
cursor.close()
connection.close()
except Exception as error:
print("Error connecting to the database:", error)
if __name__ == "__main__":
connect_to_db()
Testing the Script
Run the Python script to verify that the connection works correctly:
python script.py
You should see a message confirming the connection and the database version.
Conclusion
We configured PostgreSQL in Docker using Docker Compose and created a Python script to interact with it. This approach simplifies database management for developing and testing Python applications.