Mysql – Does Apache web service restart close existing MySQL connections

apache-2.2MySQLPHP

In the case of 'too many connections' error, if I do a service httpd restart/reload, would it free up the existing MySQL connections?

Is it possible that when restarting Apache, Apache closes the DB Connections but does not inform mysqld.

Note: mysqld has wait_timeout = 8 hours.

Best Answer

The short answer is yes, but not directly. In any case, I would consider reducing your MySQL wait_timeout to something more realistic like 30 seconds.

Apache is a web-server, it accepts HTTP connection requests and serves content back to the client - it cannot natively connect to a MySQL database.

The most likely source of your connections is an application which generates responses to those requests, i.e. a PHP, Java, Python, etc - you've tagged your question with php so I'll assume PHP here.

Now, also assuming you use Apache's mod_php rather than PHP-FPM, then PHP processes are forked by Apache, and so when you restart Apache, these processes are killed and respawned. If you were running PHP-FPM, restarting Apache would not kill any PHP processes as FPM runs as its own daemon.

In the case of a PHP process being killed via mod_php, it does not call mysql_close() to close the connection directly, and so the connection will be kept open for wait_timeout seconds.

You can tell Apache to do a "graceful" restart and allow existing threads to exit before termination, using service httpd graceful or apachectl -k graceful.

However, if your PHP code is not closing the connection via mysql_close() then that will be the ultimate source of your problem and restarting Apache via any method will not solve the issue.

Also, an important distinction to make with restart vs reload - the former terminates processes, the latter simply reloads configuration. If you really want to terminate processes, use restart.