A linux swap partition becomes useful when your server's RAM gets full. When your RAM gets full, then your swap partition will act as a RAM for your other applications. But does not this mean this is a great alternative to having a large RAM, because a swap partition on a hard drive (even SSD) can never be as fast as a RAM from a hardware point of view.
Step 1 : Check for any existing SWAP on the server by running the following command
sudo swapon -s
If you get the following output, that means you DO NOT have any swap space allocated as of now
Filename Type Size Used Priority
You may also check for swaps on the server using
Should show Swap values as zero :
total used free shared buffers cached Mem: 3998 1483 2515 64 93 1089 -/+ buffers/cache: 300 3698 Swap: 0 0 0
Step 2 : Once we have established that there are no existing swaps on the server, we will then check for the available space on the server
This will show the server disk usage in the following format :
Filesystem Size Used Avail Use% Mounted on /dev/xvda 89G 1.9G 86G 3% / none 4.0K 0 4.0K 0% /sys/fs/cgroup devtmpfs 2.0G 4.0K 2.0G 1% /dev none 400M 212K 400M 1% /run none 5.0M 0 5.0M 0% /run/lock
Step 3 : Once we have established that there is sufficient space on the server disk to create a swap, we will create our swap file, in the root directory.
cd / sudo dd if=/dev/zero of=/swapblock bs=256M count=4
The above mentioned 'dd' command will specify 4 blocks each of size of 256 Megabyte. Totalling to a swap size of 1 GB. It should provide an output in the following format
4+0 records in 4+0 records out 1294728296 bytes (1.3 GB) copied, 6.6227 s, 231 MB/s
To check that the swap has been allocated correctly, execute the following command
ls -lh /swapblock
This should display the swap block with it's size
Step 4 : Now the swapblock is created and the space has been allocated on the server, but the system does not know what to do with the space allocated yet. To solve this we will enable the swap on your ubuntu 14.04 server.
sudo mkswap /swapblock
This command will set up the swap space on the ubuntu server. It should display an output of the format
Setting up swapspace version 1, size = 1194300 KiB no label, UUID=e2f1e9cf-c0a9-4ed4-b8ab-714b8a7d6944
Once the swap space is set up, we will then enable it
sudo swapon /swapblock
This will enable the swap file on your Ubuntu 14.04 server.
Step 5 : Check that the Swap file is enabled on the server
sudo swapon -s
This should display an output like
Filename Type Size Used Priority /swapblock file 1194300 0 -1
Step 6 : Once we have confirmed that the swap file is setup and enabled, we then need to make the swap permanent on the server, so that we do not loose the changes if the server is reboot or restarted.
Open the fstab file using your favourite editor. We will use nano for this example.
sudo nano /etc/fstab
and add the following line at the bottom of this file
/swapblock none swap sw 0 0