How to Add Swap Space on EC2 Ubuntu 22.04

Creating a swap space on an EC2 instance running Ubuntu 22.04 is an essential task when you need more virtual memory. Swap allows the system to utilize disk space to store data temporarily that the RAM can’t hold. This guide illustrates how to add swap space to your Ubuntu 22.04 instance on AWS EC2.

Step-by-Step Guide

Step 1: Connect to Your EC2 Instance

Before we begin, ensure you have SSH access to your instance. Use the following command to connect:

ssh -i /path/to/your-key.pem ubuntu@your-ec2-ip

Replace /path/to/your-key.pem with the path to your key file and your-ec2-ip with your instance’s IP address.

Step 2: Check the System for Swap Information

First, check if any swap files already exist:

sudo swapon --show

If nothing is returned, you do not have active swap spaces.

Additionally, inspect free memory with:

free -h

Step 3: Create a Swap File

Decide on the amount of swap space you require. As an example, let’s create a 1GB swap file:

sudo fallocate -l 1G /swapfile

After creating the file, secure it by setting correct permissions:

sudo chmod 600 /swapfile

Step 4: Set Up the Swap Space

Initialize the file as swap space:

sudo mkswap /swapfile

Then, enable the swap file:

sudo swapon /swapfile

Verify that the swap is active:

sudo swapon --show

Step 5: Make the Swap File Permanent

To ensure the swap file persists after a reboot, edit the /etc/fstab file:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Step 6: Adjust Swap Settings (Optional)

Tweak the swappiness value (how often your system swaps data out of RAM) and the cache pressure behavior. The default swappiness value is 60; values closer to zero will use the swap less frequently.

Check the current swappiness value:

cat /proc/sys/vm/swappiness

Edit the swappiness value by editing the /etc/sysctl.conf file:

sudo nano /etc/sysctl.conf

Add the line at the end of the file:

vm.swappiness=10

Similarly, you can adjust the vfs_cache_pressure, which controls the tendency of the kernel to reclaim the memory which is used for caching of directory and inode objects:

vm.vfs_cache_pressure=50

Save and close the file. These settings will apply on the next reboot.

Step 7: Verify the Changes

Finally, ensure that everything is set up correctly:

sudo swapon --show
free -h

The output should now reflect your swap space settings, as shown below:

How to Add Swap Space on EC2 Ubuntu 22.04

Conclusion

You have successfully added swap space to your EC2 Ubuntu 22.04 instance. This can help in situations where your instance runs out of RAM, particularly important for systems with limited memory or those running applications that are prone to memory leaks.

Remember to monitor your system’s performance and adjust the swap settings as necessary to optimize system responsiveness and stability.

Happy swapping!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.