When greeted with a MySQL error this morning stating that a database connection could not be made from our PHP web application I had to do some testing. First, try connecting to the database. I did this from a remote host and was thrown back an “Error: too many connections.”
From there you should login as root from the localhost and issue:
SHOW FULL PROCESSLIST;
This will give a list of the connections. Take a good look at the big offenders because you’ll need to troubleshoot that application later and find out why it has so many connections. Now that you know the problem, restart your MySQL and connections should resume as normal (with the excessive stale connections released) and you can go about the repair.
Also, in your my.cnf you can reduce the wait_timeout which will reduce the amount of time a connection can be held open by an application. The default is 28800 seconds, or 8 hours. I reduced mine to 30 minutes. You could go less but we have some apps that do their own connection pooling and don’t want to mess that up. In my.cnf:
wait_timeout = 1800
If you are absolutely sure you need more connections, you can increase this from the default 151 in your my.cnf as well:
# default max_connections is 151 (1 spare for super user) max_connections = 201
Now you need to keep an eye on the situation by issuing the SHOW FULL PROCESSLIST once in a while to see if they are filling up fast. And don’t forget to visit any applications that may be showing up in there frequently. I found two applications tha were using persistent connections, being held open for two hours, and they just didn’t need to.