Skip to main content

Enable Swap memory using swapfile in Ubuntu EC2 instance


Calculate the swap space size
As a general rule, calculate swap space according to the following: 
Amount of physical RAMRecommended swap space
2 GB of RAM or less2x the amount of RAM but never less than 32 MB
More than 2 GB of RAM but less than 32 GB4 GB + (RAM – 2 GB)
32 GB of RAM or more1x the amount of RAM
Note: Swap space should never be less than 32 MB.
Create a swap file
1.    Use the dd command to create a swap file on the root file system, where "bs" is the block size and "count" is the number of blocks. In this example the swap file is 4 GB:
$ sudo dd if=/dev/zero of=/swapfile bs=1G count=4
2.    Update the read and write permissions for the swap file: 
$ sudo chmod 600 /swapfile
3.    Set up a Linux swap area: 
$ sudo mkswap /swapfile
4.    Make the swap file available for immediate use by adding the swap file to swap space: 
$ sudo swapon /swapfile
5.    Verify that the procedure was successful: 
$ swapon -s
6.    Enable the swap file at boot time by editing the /etc/fstab file:
$ sudo vi /etc/fstab
$ /swapfile swap swap defaults 0 0

Comments