I received the following error when deploying my php application for the first time. It looks like it is timing out when attempting to connect to MySQL: Database connection failed: Connection timed out (2002)
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
Hi there,
The error “Database connection failed: Connection timed out (2002)” typically means that PHP is not able to establish a connection with your MySQL server. This could be due to several reasons. Here are a few things you can check:
Database Server is Not Running: Make sure that the MySQL service is up and running. You can check this by running the command
systemctl status mysql
orservice mysql status
(based on your system) on your server. If it’s not running, you can start it usingsystemctl start mysql
orservice mysql start
.Incorrect Connection Parameters: Make sure you’re using the correct hostname (typically “localhost” for a database on the same server), username, password, and database name in your PHP code. The database user should also have the necessary permissions on the database.
Firewall Blocking Connection: If your MySQL database is on a different server, it could be that a firewall is preventing your PHP application from establishing a connection. Check any firewall settings or security groups (if you’re using a cloud service like AWS).
Incorrect MySQL Configuration: The MySQL server might be listening on a different port, or not correctly configured to accept connections from your PHP application. Check the MySQL configuration file (typically located at
/etc/mysql/mysql.conf.d/mysqld.cnf
or/etc/my.cnf
) and verify thebind-address
andport
directives.Network Issues: There could be network issues between your PHP application and MySQL server. You can test the connection by trying to connect to the MySQL server from the command line of the server where your PHP application is hosted, using something like
mysql -u username -p -h host
.Database Server Overloaded: If the server is under heavy load, the connection request may time out before it can be established. In this case, you might need to optimize your database or server setup to handle a higher load, or consider upgrading your server if the hardware is insufficient, here is an article that you could follow:
Best,
Bobby