0

I am currently facing a problem,

I have a docker-compose that does not return errors for none of my container's logs.

However, i am still unable to reach the flask app through http://localhost:5000.

Indeed, when i try to reach it I get the error "Connection was reset".

Here is my Dockerfile:

# Séléction du runtime python pour l'image
FROM python:3.8 

# Choisis le répertoire de travail pour COPY and CMD
WORKDIR /app

# Installer les packages listés dans requirement.txt
COPY . .
RUN pip install -r requirements.txt
# Lancer l'appli quand le conteneur se lancer
CMD python app.py

The flask container:

web:
    image: application
    depends_on:
      - db
      - cache
    ports:
      - "5000:5000"
    environment:
      - FLASK_APP=app.py
      - FLASK_RUN_HOST=127.0.0.1
    volumes:
      - app_code:/code

and finally my Flask app:

from flask import Flask, request
import redis
import mysql.connector

app = Flask(__name__)

# Connect to Redis database
redis_db = redis.Redis(host="cache", port=6379)

# Connect to MySQL database
mysql_db = mysql.connector.connect(
    host="db",
    port="3306",
    user="fil_rouge",
    password="fil_rouge",
    database="test")

@app.route("/")
def index():
    # Increment the number of visits in Redis
    visits = redis_db.incr("visits")

    # Retrieve the latest messages from MySQL
    cursor = mysql_db.cursor()
    cursor.execute("SELECT message FROM messages ORDER BY id DESC LIMIT 10")
    messages = cursor.fetchall()

    return f"""
        <html>
            <body>
                <h1>Tu est le visiteur n° {visits} .</h1>
                <p>Dernier messages :</p>
                <ul>
                    {
                        "".join([f"<li>{message}</li>" for message in messages])
                    }
                </ul>
                <form method="post">
                    <input type="text" name="message" />
                    <input type="submit" value="Send" />
                </form>
            </body>
        </html>
    """

@app.route("/", methods=["POST"])
def add_message():
    # Retrieve the message from the form
    message = request.form["message"]

    # Store the message in the database
    cursor = mysql_db.cursor()
    cursor.execute("INSERT INTO messages (message) VALUES (%s)", (message,))
    mysql_db.commit()

    return "Message sent!"

if __name__ == "__main__":
    app.run(debug = True)

Thank you for your help.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    You need to `app.run(host='0.0.0.0')` or set `FLASK_RUN_HOST=0.0.0.0`. By default it only listens on the container-private localhost interface and is unreachable from outside its own container. Also see [Deploying a minimal flask app in docker - server connection issues](https://stackoverflow.com/questions/30323224/deploying-a-minimal-flask-app-in-docker-server-connection-issues) which has a more extensive explanation and more examples. – David Maze Jan 26 '23 at 10:50

1 Answers1

0

try create connection for each request, remove the global line

# Connect to MySQL database
mysql_db = mysql.connector.connect(
    host="db",
    port="3306",
    user="fil_rouge",
    password="fil_rouge",
    database="test")

and add it for each request
for example:
@app.route("/", methods=["POST"])
def add_message():
    # Retrieve the message from the form
    message = request.form["message"]
    # Connect to MySQL database
    mysql_db = mysql.connector.connect(
    host="db",
    port="3306",
    user="fil_rouge",
    password="fil_rouge",
    database="test")
    # Store the message in the database
    cursor = mysql_db.cursor()
    cursor.execute("INSERT INTO messages (message) VALUES (%s)", (message,))
    mysql_db.commit()
return "Message sent!"
Dump Eldor
  • 92
  • 1
  • 11