Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access postgresql within Docker with sqlalchemy?

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?

like image 833
user8308842 Avatar asked Mar 16 '18 16:03

user8308842


People also ask

Can SQLAlchemy be used with PostgreSQL?

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.

Which Docker command will you use to execute commands to a PostgreSQL Docker container?

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.


1 Answers

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.

like image 111
Espoir Murhabazi Avatar answered Sep 28 '22 11:09

Espoir Murhabazi