Firstly, this article mainly applies to low memory Amazon EC2 instance types such as t1.micro, m1.small and c1.medium. For example, the t1.micro Amazon EC2 instance will often have only around 500 megabytes “free” RAM on boot. The instructions below are also specific to Amazon Linux AMI, which, like CentOS, is based on RHEL (Red Hat Enterprise Linux). Yum!
Lets get started, login to your new EC2 instance as root and update all packages:
Then if you are not going to use MTA (mail transfer agent) you can disable sendmail service:
chkconfig sendmail off
service sendmail stop
Next, reduce number of getty services. Edit /etc/sysconfig/init and replace:
Install mingetty first:
yum install mingetty
then edit /etc/init/serial.conf and replace:
exec /sbin/agetty /dev/$DEV $SPEED vt100-nav
exec /sbin/mingetty /dev/$DEV $SPEED vt100-nav
Disable yum-updatesd and replace it with a simple cron job. Will save resident memory.
chkconfig yum-updatesd off
yum remove yum-updatesd
Next, create yum update cron instead. Add a new file /etc/cron.daily/yum.cron with contents:
/usr/bin/yum -R 120 -e 0 -d 0 -y update yum
/usr/bin/yum -R 10 -e 0 -d 0 -y update
chmod +x /etc/cron.daily/yum.cron
chkconfig ip6tables off
Next, disable ntpd. Run “top” and press shift + M to sort by memory usage, you’ll notice that ntpd is close to the top of the list. Its used to keep your server clock in sync. You can replace with weekly cron so you can disable the service and further reduce memory usage.
service ntpd stop
chkconfig ntpd off
chkconfog ntpdate off
Now add a new file named ntpdate-sync to the /etc/cron.weekly directory with the contents:
chmod +x /etc/cron.weekly/ntpdate-sync
To test run:
Output should be something like:
11 Oct 22:57:49 ntpdate: adjust time server 22.214.171.124 offset -0.017816 sec
These are some basic steps to lower memory consumption of first boot. More noticeable on the smaller EC2 instances.
Of course, on low-memory instances swap is especially wise. To add a 1GB swap file for example, from command line you’ll type:
dd if=/dev/zero of=/swapfile bs=1024 count=1048576
Now setup the swap file with the command:
Now enable the swap:
If you use the top command, you should now see the 1gb swap added. So now lets make swap persistent so it’s not dropped when you reboot. Edit /etc/fstab file and add this line as the last line:
/swapfile swap swap defaults 0 0
When you reboot, use the free -h or df -h command to check for swap.
Remember, adding swap can help save your server from running out of memory but if it’s already using a big chunk of swap (aka swapping), that is never good for performance. A lot can be expanded upon with regards to swap and paging/swapping. However, the point today is that stripping/tuning the AMI, as well as the services you’ve installed should always be your focus and then of course upgrade to a larger instance if all else fails.