All posts

How to Create a Swap File on CentOS/AlmaLinux?

Aug 13, 2024 2 min read Cyberison Team Updated Dec 4, 2026
In this guide
  1. Step 1: Check Existing Swap Space
  2. Step 2: Create a Swap File
  3. Step 3: Format the Swap File
  4. Step 4: Activate the Swap File
  5. Step 5: Make the Swap File Permanent
  6. Step 6: Verify the Swap File

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.

Share this guide