Python Flask Website DB Connection Problem
AnsweredHi everyone,
I'm facing a very specific and persistent database connection issue with a Python Flask application running on cPanel, and I'm hoping to get some insight from the community.
Problem Summary: My Flask application, configured via "Setup Python App," is unable to connect to the MySQL database on localhost. The application fails with a [Errno 111] Connection refused error.
Crucial Observation (The Contradiction): To rule out credential or service issues, I created a simple PHP script with the exact same database credentials, and it connects to the database on localhost without any problems.
This tells me:
-
The MySQL service is running.
-
My database username, password, and database name are all correct.
-
The host address
localhostis valid for PHP applications on this server.
Technical Details:
-
Application: Flask 3.0.3, Python 3.7.17 (downgraded for compatibility).
-
Database Connector:
PyMySQL==1.1.1 -
Cpanel App Root:
/home/myuser/pump-calculation -
DB_CONFIGinapp.py:DB_CONFIG = { "host": "localhost", "user": "tmxflow1_progadm", "password": "my_correct_password", "database": "tmxflow1_program", }
The Exact Error Message: The error from my Flask app's log file is: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
Attempts Made:
-
Confirmed
localhostis the correct host for PHP, and the user hasALL PRIVILEGESon the database. -
The
passenger_wsgi.pyis configured with the standardfrom app import app as applicationline. -
I have tried restarting and even stopping/starting the Python application multiple times after each change.
-
All file and folder permissions are set correctly (
755for directories,644for files).
My Question: Given that the PHP environment connects successfully to localhost, but the Python environment is getting an [Errno 111] Connection refused error, it seems the Python application's container or a related configuration is preventing it from reaching the MySQL service on localhost.
Could there be a specific Cpanel or Apache/Phusion Passenger configuration that isolates Python applications from the MySQL service? Is there a different internal host address that Python apps must use instead of localhost?
Any help or suggestions on how to debug this server-level issue would be greatly appreciated.
-
Hello, i found a solution to my problem and i would want to publish it too.
Here is the solution for me :
First enter the database that you are working in and open sql query page and paste that command :
SHOW VARIABLES LIKE 'socket';output for me :

put value to DB config section like this :
DB_CONFIG = {
"user": "username",
"password": "password",
"database": "database",
"cursorclass": pymysql.cursors.DictCursor,
"unix_socket": "var/lib/mysql/mysql.sock"
}
and voila, that was the fix for me.0 -
I'm glad you were able to get that working, and thanks for sharing the solution!
0
Please sign in to leave a comment.
Comments
2 comments