How To Add Swap Space In Linux – Linux Memory Extension Steps

20. Giving your Linux server more memory for running applications starts with adding a swap space partition. If you have ever run out of RAM on a Linux system, you know the frustration of slow performance or crashed processes. Learning how to add swap space in linux is a fundamental skill that can save your server from memory exhaustion.

Swap space acts as an overflow area for your system’s memory. When your RAM fills up, the kernel moves inactive pages to swap, freeing up physical memory for active applications. This guide walks you through every step, from checking current swap usage to creating swap files and partitions.

What Is Swap Space And Why Do You Need It

Swap space is disk space used as virtual memory. It extends your available memory beyond physical RAM. Without swap, your system may kill processes when memory runs low.

Most Linux distributions recommend swap for desktops and servers. Even with plenty of RAM, swap provides a safety net. It also supports hibernation, which saves the entire RAM contents to swap.

You should consider adding swap if your system frequently uses all available RAM. Database servers, web servers, and development machines often benefit from extra swap space.

Swap File Vs Swap Partition

You have two main options for swap: a swap file or a dedicated swap partition. A swap file is easier to resize and manage. A swap partition is slightly faster and more traditional.

Modern Linux systems handle both methods well. For most users, a swap file is the simplest choice. You can create it without repartitioning your disk.

How To Add Swap Space In Linux

Now let’s get into the actual steps. This section covers creating a swap file, which is the most common and flexible method. You will need root or sudo access for these commands.

Step 1: Check Current Swap Usage

Before adding swap, check what you already have. Run this command to see current swap status:

sudo swapon --show

You can also check memory usage with:

free -h

This shows total, used, and free RAM and swap. If you see zero swap, you have none configured.

Step 2: Determine How Much Swap You Need

There is no single rule for swap size. Traditional advice suggests twice your RAM. For modern systems with large RAM, that is often overkill.

A good starting point:

  • If you have less than 2GB RAM: set swap equal to double your RAM
  • If you have 2-8GB RAM: set swap equal to your RAM size
  • If you have more than 8GB RAM: 4-8GB swap is usually enough

For hibernation, you need swap at least as large as your RAM. Consider your workload and available disk space when deciding.

Step 3: Create A Swap File

Use the fallocate command to create a swap file quickly. For a 4GB swap file:

sudo fallocate -l 4G /swapfile

If fallocate is not available, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

This creates a file filled with zeros. The count parameter sets the size in megabytes.

Step 4: Set Correct Permissions

The swap file must be secure. Only root should be able to read and write it. Run:

sudo chmod 600 /swapfile

This prevents other users from accessing the file. If permissions are wrong, the system will refuse to use it as swap.

Step 5: Format The File As Swap

Use the mkswap command to prepare the file:

sudo mkswap /swapfile

You will see output confirming the swap space was created. It shows the UUID and size.

Step 6: Enable The Swap File

Activate the swap file immediately with:

sudo swapon /swapfile

Verify it is active:

sudo swapon --show

You should see your new swap file listed. The free -h command will also show increased swap space.

Step 7: Make Swap Permanent

Without this step, your swap file disappears after reboot. Add it to /etc/fstab:

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

You can also edit the file manually with a text editor. The line tells the system to mount the swap file at boot.

Adjusting Swap Swappiness

Swappiness controls how aggressively the kernel uses swap. Values range from 0 to 100. Lower values mean the system avoids swap as much as possible.

Default is usually 60. For desktops, 10-20 can improve responsiveness. For servers, keep it at 10 or lower.

Check current swappiness:

cat /proc/sys/vm/swappiness

Change it temporarily:

sudo sysctl vm.swappiness=10

Make it permanent by adding to /etc/sysctl.conf:

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

Removing Or Resizing Swap

Sometimes you need to remove or resize swap. The process is straightforward.

Disable Swap Temporarily

Run this to turn off all swap:

sudo swapoff -a

To disable only a specific swap file:

sudo swapoff /swapfile

Remove A Swap File

After disabling swap, remove the file:

sudo rm /swapfile

Do not forget to remove the /etc/fstab entry. Otherwise, you will see errors at boot.

Resize A Swap File

To resize, disable swap, delete the old file, create a new one with the desired size, and re-enable it. Follow the steps from earlier with the new size.

Creating A Swap Partition

If you prefer a swap partition, the process is different. You need free disk space or an existing partition to resize.

Step 1: Identify Available Disk

Use lsblk or fdisk -l to see your disks. Look for unallocated space or a partition you can shrink.

Step 2: Create The Partition

Use fdisk or parted to create a new partition. Set the type to Linux swap (code 82 in fdisk).

Example with fdisk:

sudo fdisk /dev/sda

Then use n for new partition, t to change type, and w to write changes.

Step 3: Format And Enable

Format the partition:

sudo mkswap /dev/sda3

Enable it:

sudo swapon /dev/sda3

Add to /etc/fstab with the partition path or UUID.

Monitoring Swap Usage

Regular monitoring helps you understand if your swap size is appropriate. Use these tools:

  • free -h – quick overview of memory and swap
  • swapon --show – detailed swap device info
  • htop or top – real-time memory usage per process
  • vmstat 1 – shows swap in/out activity

If you see high swap usage constantly, consider adding more RAM or reducing memory-hungry applications.

Common Issues And Troubleshooting

Even with careful setup, problems can occur. Here are frequent issues and fixes.

Swap File Permission Errors

If swapon fails with “insecure permissions”, run:

sudo chmod 600 /swapfile

Then try again.

Swap File Not Enabled After Reboot

Check your /etc/fstab entry. Ensure the path and options are correct. The line should look exactly like:

/swapfile none swap sw 0 0

Disk Space Issues

If you run out of disk space, swap becomes useless. Monitor disk usage with df -h. Free up space or move swap to a larger disk.

Best Practices For Swap Management

Follow these tips for optimal swap performance:

  • Place swap on a fast disk (SSD preferred over HDD)
  • Do not use swap on network drives or USB sticks
  • Monitor swap usage regularly
  • Set swappiness appropriately for your workload
  • Keep at least some swap even with plenty of RAM
  • Use a swap file for flexibility

Performance Considerations

Swap is slower than RAM because it uses disk I/O. Heavy swap usage degrades performance. If your system swaps frequently, consider upgrading RAM.

For servers running databases or real-time applications, minimize swap usage. Set swappiness very low (1-5). For desktops, a moderate swappiness (10-20) balances performance and memory availability.

SSDs handle swap better than HDDs due to faster access times. However, excessive swapping can wear out SSDs over time. Monitor SSD health if you use swap heavily.

Swap On Cloud Servers

Many cloud providers offer instances with limited RAM. Adding swap is often necessary. However, some cloud environments use ephemeral storage that disappears on reboot.

Check if your cloud server has persistent storage. If not, create a swap file on a persistent volume. Some providers also offer swap as a service through their management console.

For AWS EC2, you can attach an EBS volume and create swap there. For DigitalOcean, swap is included by default on some plans.

Automating Swap Creation With Scripts

If you manage multiple servers, automate swap creation. Here is a simple bash script:

#!/bin/bash
SWAPFILE="/swapfile"
SIZE="4G"

if [ -f "$SWAPFILE" ]; then
    echo "Swap file already exists"
    exit 1
fi

sudo fallocate -l $SIZE $SWAPFILE
sudo chmod 600 $SWAPFILE
sudo mkswap $SWAPFILE
sudo swapon $SWAPFILE
echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
echo "Swap created successfully"

Save as create_swap.sh, make executable, and run with sudo.

Frequently Asked Questions

What is the difference between swap file and swap partition?

A swap file is a regular file on an existing filesystem. A swap partition is a dedicated disk partition. Swap files are easier to resize and manage. Swap partitions are slightly faster but require repartitioning.

How much swap space do I need for Linux?

It depends on your RAM and workload. For systems with less than 2GB RAM, use double the RAM. For 2-8GB, use equal to RAM. For more than 8GB, 4-8GB is usually sufficient. If you use hibernation, swap must be at least as large as RAM.

Can I add swap space without rebooting?

Yes. You can create and enable a swap file or partition without rebooting. Use swapon to activate it immediately. Only the /etc/fstab entry requires a reboot to take effect, but you can enable swap right away.

Is it safe to remove swap space?

Yes, but only if you have enough RAM for your workload. Disable swap with swapoff -a first. Then remove the swap file or partition. Monitor system performance after removal. If you run out of memory, processes may be killed.

Does swap space wear out SSDs?

Excessive swapping can contribute to SSD wear, but modern SSDs handle moderate swap usage well. Set swappiness low to minimize writes. For heavy swap usage, consider using a dedicated swap partition on a separate SSD or HDD.

Conclusion

Adding swap space is a simple yet powerful way to improve your Linux system’s memory management. Whether you use a swap file or partition, the process takes only a few minutes. Start by checking your current swap usage, then create the appropriate swap space for your needs.

Remember to set proper permissions, enable swap, and make it permanent in /etc/fstab. Adjust swappiness to control how aggressively swap is used. Monitor your system after adding swap to ensure it helps without causing performance issues.

Now you know how to add swap space in linux. Apply these steps to your own servers and desktops. Your system will thank you when memory runs low.