How to Create a Swap File on CentOS/AlmaLinux?
In this guide
AlmaLinux server setup series. This guide is step 4 of the series.
Swap space is a dedicated area on your hard drive that serves as virtual memory. It allows your system to temporarily store data that is not actively used in RAM, helping to improve performance and prevent out-of-memory errors. This guide will walk you through creating a swap file on CentOS/AlmaLinux.
Step 1: Check Existing Swap Space
Before creating a new swap file, check if any swap space is already configured:
free -m
If the value under ‘Swap:’ is zero, there is no swap space created:
| Category | Total | Used | Free | Shared | Buff/Cache | Available |
|---|---|---|---|---|---|---|
| Mem | 7820 | 112 | 7643 | 8 | 65 | 7537 |
| Swap | 0 | 0 | 0 | — | — | — |
If any swap space is shown, you can resize it or create an additional swap file if needed.
Step 2: Create a Swap File
Create a 2GB swap file (adjust size as needed):
sudo dd if=/dev/zero of=/swap count=2048 bs=1MiB
Set the correct permissions to restrict access:
sudo chmod 600 /swap
Step 3: Format the Swap File
Format the swap file to make it usable:
sudo mkswap /swap
Step 4: Activate the Swap File
Enable the swap file:
sudo swapon /swap
Verify that the swap file is active:
free -m
Step 5: Make the Swap File Permanent
To ensure the swap file is mounted automatically after each reboot, add it to fstab:
echo "/swap swap swap sw 0 0" | sudo tee -a /etc/fstab
Reboot the system:
sudo reboot
Step 6: Verify the Swap File
After rebooting, check that the swap file is active:
free -h
The output should display the available swap space.
By following these steps, you should have successfully created a swap file on CentOS/AlmaLinux. Adjust the partition size and settings as needed based on your system’s requirements.
Keep reading
How to Safely Change SSH Port in AlmaLinux (e.g., to 2022)
Changing the default SSH port (22) helps protect your server from automated attacks. In this guide, we’ll show you how to change the SSH port safely and open the new...
Counting .tar.gz Files in a Directory on AlmaLinux
Three simple command-line ways to count .tar.gz files in a directory on AlmaLinux: ls with wc, find with wc, and grep.
How to Install Imunify360 with a 15-Day Trial on AlmaLinux?
Imunify360 is a comprehensive security solution designed to protect Linux servers from various threats. This guide will take you through obtaining a trial license,...