You'll need to determine why the database is hitting max connections. Generally, the issue isn't that the MySQL is hitting max connections, but a symptom of other problems.
It's easy to overcommit the memory resources with Apache and MySQL settings. Check out mysqltuner and apachebuddy to get an idea of whether or not you're possibly running out of memory. If your server is having to go into swap, it's a sign that you need to speed up the execution of the database queries and your application, add more memory, or split up MySQL and Apache on separate servers (if you haven't already).
You probably have sar logs available to give you some information about the resource utilization of the server.
To show processor utilization:
To show memory utilization:
# sar -r
You can also use the
-f /var/log/sa/sa## flag to specify a sar log from a previous day.
Finally, when the database connections get maxed out, you should log in to MySQL and see what's going on.
mysql> SHOW FULL PROCESSLIST;
That will give you a listing of all of the processes MySQL is handling at a given time. In particular, you want to see if there are a bunch of "sleeping" connections. If you do, then your application is likely not closing connections properly. If you're using persistent connections, stop it. If you see a lot of queries that say "locked" or "waiting for table", you need to see if converting the table from MyISAM to InnoDB is an option. Finally, if you just have some queries that are running for more than a few seconds, you need to look into optimizing those (a whole different question) and ensure you have adequate indexes for your queries. A good way to spot where you need an index is to look at your WHERE conditions and run
SELECT queries with