An AWS micro instance has 590M of RAM. Hosting some sites with Apache and Mysql on this instance requires some adjustments to avoid consuming all memory and crashing the server.
Adding a swap file
Default installation of Ubuntu 12.04 server on AWS microinstance comes without swap.
Here are the steps to a add a swap file of 1500Mb or 1.5Gb:
sudo fallocate -l 1500m /mnt/1500M.swap
sudo chmod 600 /mnt/1500M.swap
sudo mkswap /mnt/1500M.swap
...Setting up swapspace version 1, size = 1535996 KiB
...no label, UUID=bef3f3ec-d1a4-4ec5-857e-19c9ab5c1042
sudo swapon /mnt/1500M.swap
To verfiy the swap was installed:
cat /proc/swaps
To make the swap change permanent (persist on the next reboot), add the following line to the file /etc/fstab
/mnt/1500M.swap none swap sw 0 0
This is how my /etc/fstab file looks like:
LABEL=cloudimg-rootfs / ext4 defaults 0 0
/mnt/1500M.swap none swap sw 0 0
Reducing mysql memory consumption on AWS micro instance
The mysql default install on ubuntu 12.04 can consume more than 400M RAM when the server starts to get some load/traffic. That is too much for a micro instance.
You can try changing the following values in /etc/mysql/my.cnf
# key_buffer original value was 16M
key_buffer = 8M
# query_cache_size original value was 16M
query_cache_size = 4M
max_connections = 40
that should be enough. Here are other values you can try to adjust:
# query cache limit original value was 1M
query_cache_limit = 512K
## original value was 192K
thread_stack = 128K
Tunning Apache2 MaxClients
If you get a sudden spike of www requests, there is a chance that apache2 with a default configuration will consume a lot of memory.
edit the file /etc/apache2/apache2.conf find the mpm_prefork_module and reduce MaxClients value:
StartServers 5
MinSpareServers 5
MaxSpareServers 10
##MaxClients 150
## configuration for server with little memory
MaxClients 30
MaxRequestsPerChild 0
Note that this is for apache mpm_prefok, if you installed apache mpm_worked, adjust the MaxClients line in the corresponding section.
Restart the services and monitor
Finally, restart both services and check with a tool like htop:
sudo service mysql restart
sudo service apache2 restart
htop
With htop you should be able to see allocated swap, and memory consumption of every process.