-1

I am using docker-compose to build a small flask service and the database it uses. My docker-compose.yml looks something like this:

version: '3.7'
services:
    database:
        image: postgres:10.5
        restart: always
        environment:
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres
        logging:
          options:
            max-size: 10m
            max-file: "3"
        ports:
          - '5438:5432'
        volumes:
          - ./postgres-data:/var/lib/postgresql/data
          - ./sql/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    web:
      build: .
      ports:
        - "5000:5000"
      depends_on:
        - database
      volumes:
        - .:/code
      environment:
        - FLASK_APP=app.py

My app file uses some methods from another module that I try to import as usual and looks something like this

however, after I build both containers using

docker-compose up --build database web

everything seems to be working properly because I don't get any error messages, and it says:

but when I go to any that URL or any other route from my app it says that the connection was reset. Also using curl, this is all I get:

curl: (56) Recv failure: Connection reset by peer

so I have no idea what is wrong because like I said, I don't get any error messages or warnings

DatGuy
  • 377
  • 1
  • 4
  • 10

1 Answers1

2

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

change listening IP address to 0.0.0.0

127.0.0.1 is container inside localhost but not localhost of host machine. You don't able to connect container's localhost outside container

I don't know how you run application so just added couple examples:

  • if you run flask in command line
$ flask run --host=0.0.0.0
  • if you using gunicorn set host parameter in config
[server:main]
...
host = 0.0.0.0
port = 5000
...
  • If you run app via code inside python module
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)
rzlvmp
  • 7,512
  • 5
  • 16
  • 45
  • Thanks! Yes, I needed to add the host flag in my Dockerfile like you mentioned. The problem is that now my database has the same issue – DatGuy Jul 30 '21 at 06:56
  • 1
    postgres should listen `0.0.0.0` by default. You must connect `web` and `database` containers using docker internal network, so set db host and port as `database:5432` in flask settings. DB will be accessible between containers by internal host and port. In other way you need to use `127.0.0.1:5438` or `host_machine_IP:5438` to connect from outside docker servers or host machine https://stackoverflow.com/questions/37694987/connecting-to-postgresql-in-a-docker-container-from-outside – rzlvmp Jul 30 '21 at 07:14