Optimizing memory usage on Virtual Private Servers

A repost from vps.stoned-it.com:
The smaller VPS’s might be a bit limited in memory if you want to run more advanced web-setups. In this post I’ll try to give some pointers on reducing memory usage, so you can have a more feature-full environment without running out of memory:
Looking at the memory usage in a smaller VPS a few things are obvious:

  • sshd
  • mysql-server
  • apache

These processes are essential to the functioning of a VPS, but they can be tuned a lot. I’ve tuned a 80MB VPS from 4MB free back to 30MB free by making a few small modifications:

  1. Replace openssh-server and clients with dropbear, dropbear only uses 900K vs more than 3MB for OpenSSH
  2. Configure mysql for low-memory systems, by using the my.cnf recommended by vpslink
  3. Run apache’s prefork-mpm with the following settings:
    • StartServers 1
    • MinSpareServers 1
    • MaxSpareServers 5
    • ServerLimit 50
    • MaxClients 50
    • MaxRequestsPerChild 5000
  4. Disable any apache-module that you don’t really need with:
    • a2dismod <module>

Using ‘top’, and sorting on the “RES” column you can easily spot the memory hogs. Try looking for smaller or simpler alternatives for large processes.

Also consider if you need various services, or that you could possibly do without.

Update 2008/11/04: Some more pointers for reducing your memory footprint (from the perspective of a debian etch install):

  • Install ‘dash’ and make that the default shell (saves 2MB per shell)
  • Install ‘runit’ to replace init and ‘runit-run’ to replace sysv-rc
  • Install ‘socklog-run’ to replace sysklogd/syslog
  • Remove the getty’s (as you only login over ssh anyway) from /var/service and /etc/sv, then reload runit.

This resulted in (on an otherwise idle and default debian-etch minimal install) in a memory-usage of 2564kb, with the following processes running:

root 1 0.0 0.0 104 20 ? Ss 10:38 0:00 runit
root 2930 0.0 0.7 2736 564 pts/0 Ss 10:48 0:00 dash
root 3429 0.0 0.0 132 32 ? Ss 10:57 0:00 runsvdir -P /var/service log:
root 3431 0.0 0.0 108 28 ? Ss 10:57 0:00 runsv socklog-unix
log 3432 0.0 0.0 160 76 ? S 10:57 0:00 svlogd main/main main/auth main/cron main/daemon main/debug main/ftp main
root 3433 0.0 0.0 108 32 ? Ss 10:57 0:00 runsv socklog-klog
log 3434 0.0 0.0 128 40 ? S 10:57 0:00 svlogd -tt main/main
nobody 3435 0.0 0.4 2528 332 ? S 10:57 0:00 socklog unix /dev/log
root 3436 0.0 0.3 2528 300 ? S 10:57 0:00 socklog ucspi

You still have all the features, and can still use bash for your interactive shells, but you can have the memory resources free when you need them, and also still have cron, syslog and sysv-rc functionality.
You can limit diskspace usage (not mentioned up to here) by using busybox and friends and uninstalling some packages busybox replaces. However, in my experience, diskspace is less an issue than memory.