0

I have my flask app app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

APP = Flask(__name__)
DB = SQLAlchemy()

if __name__ == '__main__':
    APP.config.from_mapping(
        SQLALCHEMY_DATABASE_URI='postgres://postgres:[email protected]:5432',
        SQLALCHEMY_TRACK_MODIFICATIONS=False
    )
    DB.init_app(APP)
    DB.create_all(app=APP)
    APP.run(use_reloader=False, host='0.0.0.0', port='5000')

and I have a Dockerfile for it:

FROM python:3.6-alpine

RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev

WORKDIR /root

COPY app.py .

RUN pip3 install Flask==1.0.2
RUN pip3 install psycopg2-binary==2.7.6.1
RUN pip3 install Flask-SQLAlchemy==2.3.2

CMD ["python3", "app.py"]

I run:

docker build . --tag flaskapp:1
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password --name database postgres
docker run --rm -p 5000:5000 flaskapp:1

I then get an exception which points out:

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?

How do I fix this?

1
  • ok so I actually figured out that --network=host solves this problem. It may cause other problems but its better than not working for the moment Commented Nov 30, 2018 at 21:33

1 Answer 1

4

You have specified 0.0.0.0 as the IP address to connect to, which doesn't make sense. 0.0.0.0 is the "Any Address". You probably saw a message that postgres was listening on 0.0.0.0, which is where you got it from. In the context of a server listening on 0.0.0.0, it means that it is listening on all ipv4 interfaces. See https://en.wikipedia.org/wiki/0.0.0.0 for more information about the special 0.0.0.0 address and what it means.

If you want to connect to the postgres service, then you would need to use a valid ip address or dns name of where it is running.

In Docker, if you have multiple named containers connected to the same user-defined network, you can make use of the built-in service discovery mechanism that Docker ships with.

Here's a modified set of commands to run to take advantage of this:

docker network create mynet
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password --net mynet --name database postgres
docker run --rm -p 5000:5000 --net mynet flaskapp:1

Be sure to change your code to connect to postgres://postgres:password@database:5432 instead of postgres://postgres:[email protected]:5432

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.