How to Create, Verify, and Increase Swap Space on Linux
Swap space is disk space that Linux uses as virtual memory when physical RAM is exhausted. Proper swap configuration helps improve system stability and prevents out-of-memory situations.
PURPOSE: All documents are provided on this Blog just for educational purposes only. Please make sure that you run it in your test environment before to move on to production environment.
What is Swap Space?
Swap is a reserved area on disk that acts as an extension of RAM. When memory usage becomes high, inactive pages can be moved from RAM to swap, freeing memory for active processes.
Benefits of Swap
- Prevents application crashes due to memory shortages.
- Provides additional virtual memory.
- Supports system hibernation (when configured appropriately).
- Improves system stability during memory spikes.
Check Existing Swap Space
Use any of the following commands to verify current swap configuration and usage.
free -h
Check Active Swap Devices
swapon -s
cat /proc/swaps
swapon --show
Create a New Swap File
This method creates a 2 GB swap file. Adjust the size according to your requirements.
Step 1: Disable Existing Swap (if required)
swapoff -aStep 2: Create Swap File
sudo fallocate -l 2G /swapfileVerify file creation:
ls -lh /swapfileStep 3: Set Correct Permissions
sudo chmod 600 /swapfileVerify permissions:
ls -l /swapfileStep 4: Format the File as Swap
sudo mkswap /swapfileStep 5: Enable Swap
sudo swapon /swapfileStep 6: Verify Swap Activation
swapon --showor
free -hStep 7: Make Swap Persistent After Reboot
Add the following entry to
/etc/fstab:echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstabVerify:
cat /etc/fstabExpected entry:
/swapfile none swap sw 0 0Increase Existing Swap Partition
Current swap size: 8GBTarget swap size: 16GBStep 1: Disable Swap
swapoff -aVerify:
swapon --showNo output should be displayed.
Step 2: Increase Virtual Disk Size in vCenter
Increate hard disk 1 from 64 to 90 GB
Navigate to VMware vCenter:
VM Settings
→ Hard Disk 1
→ Increase disk sizeExample:
64 GB → 90 GBStep 3: Detect New Disk Size
Check available disk space:
fdisk -lIf the new size is not visible, rescan the disk:
echo 1 > /sys/class/scsi_device/0\:0\:0\:0/device/rescanRun again:
fdisk -lStep 4: Modify Partitions
Launch partition manager:
cfdisk
Existing Layout
/dev/sda3 Linux filesystem
/dev/sda4 Linux swapDelete Existing Swap Partition
Select:
/dev/sda4Choose:
DeleteResize Root/Data Partition
cfdiskSelect:
/ dev/sda3 # This was a root partition which we increased on vCenter.Choose:
Resize ==> WriteCreate New Swap Partition
Use remaining free space:
New
Type → Linux swap
mkswap /dev/sda4 Setting up swapspace version 1, size = 26 GiB (27917262848 bytes) no label, UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # edit the UUID vi /etc/fstab mount -a swapon /dev/sda4 swapon --show NAME TYPE SIZE USED PRIO /dev/sda4 partition 26G 0B -2