How-To: Create a Swap file on Ubuntu 12.04
Posted by Wayne on Sunday, 16 February 2014
I've been using DigitalOcean for a few weeks now and have been very happy so far. In fact I've only run into one issue, with MySQL crashing. At first it looked like an issue with the specific blogging platform I'm using, but the mysql log file quickly cleared that up.
InnoDB: Fatal error: cannot allocate memory for the buffer pool
The problem of course is a shortage of memory, the basic DigitalOcean droplet only has 512mb and can quickly be eaten up by a LAMP stack when there is a lot of traffic. I have to assume that this would be a common issue across cloud providers at the basic level (aws free tier, rackspace, etc.) Which means, there are two possible solutions. 1. increase the size of the server, which would cost more. Or, create a swapfile to prevent mysql crashing.
The following steps are specific to Ubuntu 12.04, but should work across most distributions.
Check if there is currently swap space enabled:
- sudo swapon -s # Will show an empty list if there is no swap space enabled
- if there is active swap you can disable it with:
- sudo swapoff -a
Check the file system for free space:
Create and enable the swap file:
- sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
- bs is reading / writing 1024 BYTES at a time
- count is the number of input BLOCKS. In this case 1024 x 1024MB resulting in 1GB of swap space
- sudo mkswap /swapfile # Will return a message "setting up swapspace version1 1 ..."
- sudo swapon /swapfile
Verify the swapfile is active:
- swapon -s
Add the swap to the fstab:
- sudo vim /etc/fstab
- /swapfile none swap sw 0 0
In order to make the swap act as a emergency buffer, prevent out-of-memory crashes, and improve performance, set the swappiness to 0:
- sudo echo 10 | sudo tee /proc/sys/vm/swappiness
- sudo echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf
Prevent the swap file from being world readable.
- sudo chown root:root /swapfile
- sudo chmod 0600 /swapfile