pythonmysqllinuxapacheflask

Unable to make a remote api call to flask app(for MySQL connection) inside my apache server


I have an apache server running on Alma Linux. I have the flask code setup to accept API calls from remote connections. So my API call hits the flask which then connects to MySQL database.

When I try to run this database connection code locally inside the server, it works fine. But when I try to hit flask app via remote API call, I get

Database error: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (13)

This is very strange since I can connect to the database locally inside the server.

I also wrote a dummy endpoint.

@app.route('/')
def test_endpoint():
        return 'Hello World'

This endpoint works from the remote API call.

My code for connecting to database

import mysql.connector
from flask import Flask

app = Flask(__name__)
df_config = {connection parameters}

@app.route('/db_test', methods=['GET','POST'])
def db_test():

  try:
     conn = mysql.connector.connect(**db_config)
     return Statement

  except Error as e:
     return jsonify({'success': False, 'message': f"Database error: {e}. Contact the researcher"}), 500  

I checked MySQL is running on port 3306 and I have the necessary database permissions. I also tried commenting "bind-address = 127.0.0.1" in MySQL config file.

Kindly help me with a fix.


Solution

  • Too long to be a comment, but thus us not going to be a full answer either as I don't think you have a programming problem that can be solved via programming changes.

    The error message in the question is produced by mysql client trying to use a socket connection to connect to a mysql server. When the connection fails, it returns the socket error number (13) besides the generic error message.

    Socket error 13 stands for "permission denied". This means the mysql client does not have the right to use network connections. Mysql client is part of flask / python, but flask is run by your web server, apache.

    You have two options:

    1. As mysql server is hosted on the same computer as apache, use a sock file connection as opposed to using sockets. There are several examples how to do thid here on SO.

    2. You need to granr apache webserver or to the user account in whoch name apache runs in, the right to use socket connections. Serverfault sister site of SO can help you with this.