I'm trying to interact with a dockerized PostgreSQL server using SQLAlchemy. Something like:
engine = create_engine('postgresql://user:user_password@localhost:5432/database')
df.to_sql('table', engine)
Which gives me this error:
OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
Which suggests the Docker postgresql (which is running) isn't available at that port. I've tried adding -p 5432:5432
to my docker-compose exec
without success. Any tips?
This SQLAlchemy engine is a global object which can be created and configured once and use the same engine object multiple times for different operations. The first step in establishing a connection with the PostgreSQL database is creating an engine object using the create_engine() function of SQLAlchemy.
You can use Docker Compose to configure the Postgres as a service running inside of a container. In that case, you create a yaml file with all the specifications.
As your flask app and Postgres images are not in the same docker container you cannot access the database via localhost !!
in your database URL replace localhost the name of Postgres Service in docker-compose/
engine = create_engine('postgresql://user:user_password@{}:5432/database'.format('service_name_of_postgres'))
kudos to this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With