I want to run and connect to the postgresql Docker image in Python using SQLModel. Here's my attempt
from contextlib import contextmanager
import docker
from sqlmodel import create_engine, SQLModel, Field
DEFAULT_POSTGRES_PORT = 5432
class Foo(SQLModel, table=True):
id_: int = Field(primary_key=True)
@contextmanager
def postgres_engine():
db_pass = "foo"
host_port = 1234
client = docker.from_env()
container = client.containers.run(
"postgres",
ports={DEFAULT_POSTGRES_PORT: host_port},
environment={"POSTGRES_PASSWORD": db_pass},
detach=True,
)
try:
engine = create_engine(
f"postgresql://postgres:{db_pass}@localhost:{host_port}/postgres"
)
SQLModel.metadata.create_all(engine)
yield engine
finally:
container.kill()
container.remove()
with postgres_engine():
pass
I'm seeing
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (127.0.0.1), port 1234 failed: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
If instead of using the Python Docker SDK I use the CLI with
docker run -it -e POSTGRES_PASSWORD=foo -p 1234:5432 postgres
I don't see an error.