Creating a swap partition on an Amazon Elastic Compute Cloud (EC2) instance can help improve the performance and stability of your system. A swap partition is a space on the hard drive that can be used by the operating system as virtual memory when the physical memory (RAM) is running low.
In this article, we will explain how to create a swap partition on your EC2 instance.
- Check if your EC2 instance has a swap partition
Before creating a swap partition, you should check if your EC2 instance already has one. To do this, you can run the following command in the terminal:
sudo swapon -s
If you see output that lists a swap file or partition, then your instance already has a swap partition.
- Determine the amount of swap space you need
The amount of swap space you need depends on the amount of physical memory (RAM) on your EC2 instance and the amount of memory-intensive applications you plan to run. As a general rule, the swap space should be at least equal to the amount of RAM on the instance.
To determine the amount of RAM on your instance, you can run the following command in the terminal:
This will display the amount of memory (in megabytes) on your EC2 instance. To calculate the amount of swap space you need, simply multiply the amount of RAM by 2.
- Create a swap file
To create a swap file on your EC2 instance, you can use the fallocate command. The following command will create a 2 GB swap file named /swapfile:
sudo fallocate -l 2G /swapfile
If the fallocate command is not available on your instance, you can use the dd command instead:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
This command will also create a 2 GB swap file named /swapfile.
- Set the correct permissions on the swap file
The swap file should only be accessible by the root user. You can set the correct permissions using the following command:
sudo chmod 600 /swapfile
- Set up the swap space
To set up the swap space, you need to use the mkswap command. The following command will set up the /swapfile as swap space:
sudo mkswap /swapfile
- Enable the swap space
To enable the swap space, you can use the swapon command. The following command will enable the /swapfile swap space:
sudo swapon /swapfile
- Make the swap space permanent
By default, the swap file will not be enabled on system reboot. To make the swap space permanent, you need to add an entry to the /etc/fstab file. Open the file with a text editor:
sudo nano /etc/fstab
Add the following line at the end of the file:
Save and exit the file. The swap file will now be enabled on system reboot.
That’s it! You have now created a swap partition on your EC2 instance. This should help improve the performance and stability of your system, especially when running memory-intensive applications.