Create a 4 GB Swap File

Linux September 25, 2026 21 Views 1 min read
Create a 4 GB Swap File

Swap provides disk-based virtual memory that Linux can use when physical RAM becomes heavily utilized. The following commands create a 4 GB swap file, enable it immediately, and configure it to be enabled automatically after a reboot.

Step 1: Create the Swap File

sudo fallocate -l 4G /swapfile

Step 2: Secure the Swap File

Restrict access to the swap file so that only root can read or modify it:

sudo chmod 600 /swapfile

Step 3: Format the File as Swap

sudo mkswap /swapfile

Step 4: Enable Swap Immediately

sudo swapon /swapfile

Step 5: Enable Swap After Reboot

Add the swap file to /etc/fstab:

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

Step 6: Set Lower Swappiness

Set the current kernel swappiness value to 10:

sudo sysctl vm.swappiness=10

Make the setting persistent across reboots:

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Verify the Swap Configuration

swapon --show
free -h
sysctl vm.swappiness

You should see /swapfile listed as active swap and the swappiness value set to 10.

Result: The server now has a 4 GB swap file that is enabled immediately and configured to remain available after reboot.

 

Discussion (0)