Solution for Low Memory on Small Servers: Configuring Swap Space on AWS EC2

As a self-hosting enthusiast, I enjoy deploying various web services for personal use. On a single AWS EC2 instance, I’ve hosted multiple services including Nextcloud, WordPress, Postfix, Dovecot, MariaDB, and Nginx.

However, with only 1GB of RAM, I frequently encountered MariaDB database crashes due to “Out of Memory” (OOM) errors. To address this, setting up Swap Space is an effective solution to significantly reduce service interruptions. While using a hard drive for Swap may slightly decrease caching performance, the trade-off is well worth it for personal use—exchanging a bit of speed for continuous service availability.


Step 1: Prepare the Disk Volume in AWS Console

Before configuring the OS, you need to provide the physical storage:

  1. Go to the AWS EC2 Console.
  2. Create a new EBS Volume. I recommend setting the size to twice your RAM (e.g., 2GB for a 1GB instance).
  3. Attach this volume to your instance.

Step 2: Identify the New Partition

Connect to your server via SSH and use the following command to identify your new block device:

lsblk

In my case, nvme0n1 is the new partition designated for SWAP. You should see your newly added storage partition listed in the output.

Step 3: Format and Enable Swap

Once you have identified the device name, execute the following commands to format it as swap space and activate it:

# Format the partition as swap
sudo mkswap /dev/nvme0n1

# Enable the swap space
sudo swapon /dev/nvme0n1

Verification

To confirm it is working, run lsblk again. If you see [SWAP] under the MOUNTPOINTS column, it means the partition is successfully attached.

You can also use the top command to monitor the swap usage in real-time:

top

Step 4: Configure Persistent Mount (Auto-mount on Boot)

To ensure the swap remains active after a reboot, you must add it to the file system table (/etc/fstab). It is best practice to use the UUID for stability.

  1. Find the UUID of your swap partition:
    sudo blkid
    Locate your partition (e.g., /dev/nvme0n1) and copy the UUID string.

  2. Edit the fstab file:
    sudo nano /etc/fstab
  3. Add the following line at the end of the file:
    UUID="YOUR-UUID-HERE" none swap sw 0 0

    Note: Replace YOUR-UUID-HERE with your actual UUID. Be careful with this step, as errors in this file can cause boot issues.

  4. Press Ctrl + X, then Y, and Enter to save and exit.

Conclusion

By adding a simple 2GB swap partition, your small AWS instance can handle memory spikes much more gracefully. No more worrying about MariaDB crashing in the middle of the night!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料