How to configure Swap Space in Linux

April 17, 2025 / Servers, Hosting & Email

This article explains how to configure Swap Space in Linux. It is important for managing memory efficiently during heavy workloads. Swap space acts as a backup for physical RAM and can be set up as a swap file or a dedicated partition.

Follow the below steps to configure swap space:

  1. Check existing Swap Space before adding it:
    1.  Show swap details:
      $ sudo swapon --show
    2. View overall memory usage:
      $ free -h

      If no output is returned, swap space is not configured.

  2. Creating a Swap File
    To add swap space without changing partitions, follow these steps:

    1. Create the Swap File:
      $ sudo dd if=/dev/zero of=/swapfile bs=1M count=1024

      Replace 1024 with the desired size in MB (e.g., 2048 for 2GB).

    2. Set File Permissions:
      $ sudo chmod 600 /swapfile
    3. Format the File as Swap:
      $ sudo mkswap /swapfile
    4. Activate the Swap File:
      $ sudo swapon /swapfile
    5. Make it Permanent: Add this line to /etc/fstab:
      /swapfile none swap sw 0 0
  3.  Configuring a Swap Partition
    For long-term performance, a dedicated swap partition is often chosen:

    1. Identify or Create a Partition:
      List available partitions using:

      $ sudo fdisk -l

      Create a new partition using fdisk or a similar tool, and set its type to Linux swap (type 82).

    2. Format the Partition:
      $ sudo mkswap /dev/sdX

      Replace /dev/sdX with your partition’s identifier (e.g., /dev/sda3).

    3. Activate the Swap Partition:
      $ sudo swapon /dev/sdX
    4. Make it Persistent: Add this line to /etc/fstab:
      /dev/sdX none swap sw 0 0
  4. Adjusting Swap Settings
    1.  Check current “swappiness” value (controls swap usage frequency):
      $ cat /proc/sys/vm/swappiness
    2. Temporarily adjust swappiness:
      $ sudo sysctl vm.swappiness=10
    3. For permanent changes, add this to /etc/sysctl.conf:
      swappiness=10

This way, you can configure swap space as it ensures stable performance, especially for memory-intensive tasks or servers. If you need assistance, feel free to contact our support staff.

Running low on space? Learn How to increase disk space for a domain in Linux reseller account

Spread the love