6

Using docker-compose, I'm trying to view a Flask app from manage.py runserver that connects with a postgres image but I get the following error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
    Is the server running on host "0.0.0.0" and accepting
    TCP/IP connections on port 5432? 

MY COMPOSE FILE

version: '3.1'
services:
  app:
    build: .
    ports:
      - 5000:5000
    volumes:
      - /Users/sammy/Projects/my_flask_app:/my_flask_app
    container_name: my_flask_app_1
    depends_on:
      - db
    entrypoint: ["python", "manage.py", "runserver"]
  db:
    image: postgres:10
    restart: always
    container_name: my_app_db_1
    environment:
      POSTGRES_USER: ubuntu
      POSTGRES_PASSWORD: pickles
      POSTGRES_DB: db
    ports:
      - 5432:5432

FROM MY APP'S settings.py FILE

POSTGRES = {
    'user': "ubuntu",
    'pw': "pickles",
    'db': "db",
    'host': os.getenv('IP', '0.0.0.0'),
    'port': '5432',
}
SQLALCHEMY_DATABASE_URI = 'postgresql://%(user)s:\
%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES

It builds and runs the app well as I can visit the site and see the Werkzeug traceback interpreter. I'm failing either on the configuration of the Postgres container itself or my Flask's connection to it.

  • Are the environmental variables correct?
  • Do I need to specify a volume for the DB? If so, why? I haven't understood the point of that other than tucking the username/pass into environmental variables.
1
  • You host should be "db" Commented May 31, 2018 at 15:10

1 Answer 1

12

Your host in the settings.py file should be "db". compose exposes hosts on an internal network with the same host names as your services.

POSTGRES = {
    'user': "ubuntu",
    'pw': "pickles",
    'db': "db",
    'host': "db",
    'port': '5432',
}
Sign up to request clarification or add additional context in comments.

2 Comments

Are you suggesting I add a -host flag to my compose file? Do you know any any examples I could reference?
Thanks. I didn't realize the name of the service was the container's hostname. That's huge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.