0

mysql.connector returns "mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)" when making request to local mysql with python/flask file in docker container

I have a python file running a flask server, meant to handle authentication. This flask server running on localhost:5000 queries mysql (which runs on localhost:3306 I think). I'm using the mysql.connector package that gets installed via pip3 install mysql-connector-python. This mysql connection always works when running the flask server on localhost:5000 from my computer normally but fails to do so when I run it on the same port but via a docker container also running on localhost:5000. Here's my code:

from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import mysql.connector

app = Flask(__name__)
CORS(app)

@app.route('/login', methods=['post'])
@cross_origin(origin="*")
def login():
    db = mysql.connector.connect(
      host="localhost",
      user="root",
      password="********",
      database="********"
    )
    con = db.cursor()
    data = request.get_json()
    print("Username: " + data["usr"] + ', Password: ' + data["pass"])
    con.execute("SELECT id, pass FROM Users WHERE id = '{}' AND pass = '{}'".format(data["usr"], data["pass"]))
    if con.fetchone() != None:
      return "loginSuccess"
    else:
      return "loginFail"

This runs on localhost:5000 by virtue of flask defaults. And on docker, I run the docker container of this python file on localhost:5000 with the flask application within the container running on localhost:5000 as well by having CMD exec gunicorn --bind :5000 --workers 1 --threads 8 app:app in my dockerfile. PS, my python file is in fact called app.py, in accordance with the gunicorn command.

I've seen other threads suggesting that docker containers can't connect with mysql but the only solutions in those threads are to people connecting to sql via sql in the terminal, not by any mysql connectors in python.

0 Answers0