Sobes.tech
Junior — Middle

Have you used containerization for connecting and working with a database in Docker?

sobes.tech AI

Answer from AI

Yes, containerization using Docker is often used to run databases in an isolated environment, which simplifies setup and dependency management. For example, you can run a container with PostgreSQL and connect to it from a Python application.

Example of running PostgreSQL in Docker:

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres

In Python, you can connect to this database using the psycopg2 library:

import psycopg2

conn = psycopg2.connect(
    dbname='postgres',
    user='postgres',
    password='mysecretpassword',
    host='localhost',
    port=5432
)

cursor = conn.cursor()
cursor.execute('SELECT version();')
print(cursor.fetchone())

cursor.close()
conn.close()

This approach makes it easy to run and test databases locally without installing them directly on the machine.