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:
- Go to the AWS EC2 Console.
- Create a new EBS Volume. I recommend setting the size to twice your RAM (e.g., 2GB for a 1GB instance).
- 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.
- Find the UUID of your swap partition:
Locate your partition (e.g., /dev/nvme0n1) and copy the UUID string.sudo blkid - Edit the fstab file:
sudo nano /etc/fstab - Add the following line at the end of the file:
UUID="YOUR-UUID-HERE" none swap sw 0 0Note: Replace
YOUR-UUID-HEREwith your actual UUID. Be careful with this step, as errors in this file can cause boot issues. - 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!