All Products
Search
Document Center

:How do I configure a swap partition for a Linux instance?

Last Updated:Dec 23, 2025

When an Elastic Compute Service (ECS) instance runs low on physical memory, configuring a swap partition is a cost-effective emergency solution that uses disk space as virtual memory. This can prevent the system from crashing due to an out-of-memory (OOM) error during occasional memory spikes and helps the system continue to operate when physical memory is exhausted.

Important
  • Enabling a swap partition can decrease memory I/O performance. If your ECS instance frequently runs out of memory, the primary solution is to increase its physical memory by changing the instance type.

  • Do not use a swap partition on a basic disk. Its low I/O performance can cause performance degradation and I/O bottlenecks. For other disk types, you can use a swap partition as needed. However, you must configure it properly to avoid frequent swapping, which can negatively impact system performance and stability.

Procedure

Step 1: Check the current Swap status

Before you begin, confirm that the system does not have an existing swap configuration to avoid conflicts.

  1. Log on to the ECS instance.

    1. Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.

    2. Go to the details page of the target instance. Click Connect and select Workbench. Follow the prompts on the page to log on to the terminal.

  2. Check the swap partition configuration.

    swapon --show
    • If the output is empty, the system does not have a swap partition configured. You can proceed to the next step.

    • If output similar to the following is returned, the system already has a swap partition. You can disable the swap partition if needed, or create a new swap file on another disk.

      image

Step 2: Create and set up the Swap file

  1. Create a swap file.

    This example creates a 1 GiB swap file named /swapfile using the fallocate command. This command allocates file space instantly and is more efficient than dd.

    # Create a 1 GiB swap file
    sudo fallocate -l 1G /swapfile
    If the file system, such as an early version of XFS, does not support fallocate, the system returns the message fallocate failed: Operation not supported. In this case, use the dd command instead. This command takes longer to run.
    sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
    • The value of of, /swapfile, is a variable that represents the path and name of the swap file. You can customize this value, but it cannot be the same as an existing file or partition name.

    • The values of bs and count determine the size of the swap file. You can customize these values. In this command, bs=1M count=1024 sets the swap file size to 1 GB.

  2. Set secure permissions.

    Set the permissions of the swap file to 600. This prevents non-root users from reading the swap file, which might contain sensitive data, such as passwords or keys, that has been swapped out of memory.

    sudo chmod 600 /swapfile
  3. Format the file as a swap area. This marks the file for use as swap space.

    sudo mkswap /swapfile

    A successful response is similar to the following:

    Setting up swapspace version 1, size = 1 GiB (1073737728 bytes)
    no label, UUID=a1a7e24c-38f6-41a4-9e18-be60b631133a
    Note: The swap file must be larger than 40 KB. Otherwise, the mkswap command returns an error.

Step 3: Enable and verify Swap

Activate the swap file and confirm that the system recognizes it.

  1. Activate the swap file.

    sudo swapon /swapfile
  2. Verify that the swap file is enabled.

    swapon --show

    After this is successfully enabled, the following appears:

    NAME       TYPE SIZE USED PRIO
    /swapfile  file   1G   0B   -2

    Alternatively, you can run the free -h command to check the swap status. The Swap row in the output shows the total swap space.

Step 4: Configure automatic mount on startup (persistence)

Add the swap configuration to the /etc/fstab file to ensure that the swap file remains active after the instance restarts.

  1. (Recommended) Back up the fstab file to prevent issues that may arise from incorrect operations.

    sudo cp /etc/fstab /etc/fstab.bak.$(date +%Y%m%d)
  2. Append the swap configuration to the fstab file.

    The following command first checks for duplicate entries to avoid adding the same configuration twice.
    SWAP_FILE_PATH="/swapfile"
    if ! grep -q "swap" /etc/fstab; then
        echo "${SWAP_FILE_PATH} none swap sw 0 0" | sudo tee -a /etc/fstab
    else
        echo "Swap entry already exists in /etc/fstab. No changes made."
    fi
  3. Verify the persistent configuration.

    You can verify that the /etc/fstab configuration is correct without restarting the instance.

    # 1. Disable all Swap.
    sudo swapoff -a
    # 2. Remount all Swap based on the fstab content.
    sudo swapon -a
    # 3. Check if Swap has been remounted as expected.
    swapon --show

    If the command correctly outputs the swap information, the persistent configuration is successful.

Optimization and management

Adjust the Swap usage tendency (swappiness)

swappiness is a Linux kernel parameter that controls how aggressively the system uses swap space. Its value ranges from 0 to 100.

  • Higher value: The kernel is more likely to use swap space and swaps out inactive memory pages to the disk sooner.

  • Lower value: The kernel is less likely to use swap space. It prefers to keep memory pages in physical memory and only uses swap space when physical memory is critically low.

Important

Adjusting the swappiness parameter is an operation that requires caution. An improper modification might lead to system performance degradation or unexpected virtual memory usage. You should perform this operation only if it is required for your business scenario and you have a full understanding of the parameter's function. If you are unsure whether an adjustment is needed, we recommend that you keep the default configuration.

Scenario-based recommendations:

Application scenario

Recommended swappiness value

Technical principle

Databases (MySQL, PostgreSQL)

1-10

Databases are sensitive to I/O latency. Avoid swapping out their core buffer pools to ensure query performance.

In-memory databases (Redis, Memcached)

1

In-memory databases are extremely sensitive to latency. Any Swap operation can severely impact performance. A value of 1 means Swap is used only when absolutely necessary.

Web application servers (Nginx, Apache)

10-60

Balances response speed and memory utilization. Allows non-core, inactive process pages to be swapped out.

Default/General/Batch processing

60 (system default)

Suitable for most general-purpose scenarios. Allows the system to swap out inactive system processes to free up more physical memory for active tasks.

Modification method:

  1. Edit the /etc/sysctl.conf file. This example adjusts the parameter value so that the swap partition is used only when the available physical memory is less than 10% of the total.

    vm.swappiness=10
  2. Save and exit the file. Then, run the following command to apply the configuration.

    sudo sysctl -p
  3. Run the following command to verify that the swappiness parameter configuration is effective.

    cat /proc/sys/vm/swappiness

    Output similar to the following indicates that the swappiness parameter configuration is effective.

    image

Monitor Swap usage

Monitoring purpose

Recommended command

Description

View overall memory and Swap usage

free -h

The most common and straightforward command.

Monitor real-time Swap activity (swap-in/swap-out)

vmstat 1

Focus on the si (swap-in) and so (swap-out) columns. If these columns consistently show non-zero values, the system is frequently swapping. This may indicate a performance issue.

Find processes that are using Swap

`for file in /proc/*/status; do awk '/VmSwap

Name/{printf 2""2""3}END{ print ""}' $file; done | grep -v "0 kB" | sort -k 2 -n -r

Historical performance analysis

atop

atop is a powerful performance monitoring tool that can record historical resource usage. When the system is stuttering, you can use atop logs to trace the processes and resource status at the time the issue occurred.

Disable and clean up Swap

When the swap file is no longer needed, you can safely disable it and delete the file to free up disk space.

  1. Disable the specified swap file.

    sudo swapoff /swapfile
  2. Remove the automatic mount configuration from /etc/fstab. You can use the sed command to safely delete the corresponding line and avoid manual editing errors.

    sudo sed -i '\|/swapfile|d' /etc/fstab
  3. Delete the swap file to release disk space.

    sudo rm /swapfile
  4. Verify that the swap file is completely disabled.

    Run the swapon --show or free -h command and confirm that the swap information is no longer displayed.

Disable a swap partition

  1. Run the following command to disable the swap partition.

    sudo swapoff /swapfile
    Note

    The /swapfile parameter specifies the swap partition identifier. Replace it with the actual identifier from your environment.

  2. Edit the /etc/fstab file and delete the swap mount information, such as the following entry, to disable automatic mounting.

    /swapfile none swap defaults 0 0
  3. Save and close the file. Then, run the following command to check if the swap partition is disabled.

    swapon --show

    If the command output is empty, the swap partition is disabled.

    image

FAQ

What should I do if Swap does not behave as expected?

After you create a swap partition and adjust the swappiness parameter, you might notice that the swap partition's usage remains low even when physical memory is under heavy pressure. This can make it seem as if the swappiness setting has no effect.

Problem diagnosis

The root cause of this issue is related to the systemd and control group (Cgroup) mechanisms used in modern Linux distributions.

  1. Local Cgroup rules: In the default Cgroup v1 mode, systemd creates separate Cgroups for system services (system.slice), user sessions (user.slice), and other components. Each Cgroup can have its own resource control parameters, including memory.swappiness.

  2. Local settings override global settings: When systemd initializes these Cgroups, it assigns them a default memory.swappiness value, which is usually 60. This Cgroup-specific setting has a higher priority than the global vm.swappiness setting that you configure in /etc/sysctl.conf.

  3. Result: Running programs follow the swappiness rule of their Cgroup, not the global rule. This makes the global configuration ineffective.

Quick verification
  1. Find the process ID (PID) of a running process. For example, you can run the pidof nginx command.

  2. Check the Cgroup to which the process belongs:

    cat /proc/[PID]/cgroup

    The output displays a path similar to /system.slice/nginx.service.

  3. Check the actual swappiness value for this Cgroup:

    cat /sys/fs/cgroup/memory/system.slice/nginx.service/memory.swappiness

    The output is most likely 60, even if you set the global vm.swappiness parameter to a different value. This confirms that the global configuration is not being applied.

Solutions

Solution 1: Switch to Cgroup v2 (recommended)

Principle: Cgroup v2 fixes many design issues of Cgroup v1 and uses a unified hierarchy. In Cgroup v2 mode, child Cgroups inherit the configuration of their parent node by default. You only need to configure the global vm.swappiness parameter, and the setting is automatically applied to all processes in the system.

Procedure:

  1. Update the kernel boot parameters.
    Use the grubby tool to add the systemd.unified_cgroup_hierarchy=1 parameter for all kernels to enable Cgroup v2.

    sudo grubby --update-kernel=ALL --args="systemd.unified_cgroup_hierarchy=1"
    Note: This command is persistent. It modifies the GRand Unified Bootloader (GRUB) configuration to make the system initialize in Cgroup v2 mode on the next startup.
  2. Restart the ECS instance.
    This is a kernel-level parameter and requires a restart to take effect.

    sudo reboot
  3. Verify and configure:

    • Verify: After the instance restarts, run the mount | grep cgroup command. If you see a mount point with the type cgroup2, you have successfully switched to Cgroup v2.

    • Configure: In the /etc/sysctl.conf file, set the desired vm.swappiness value and run the sudo sysctl -p command to apply the setting to the entire system.

Solution 2: Persistently configure in a Cgroup v1 environment (alternative)

In cases where you cannot switch your environment, such as when running older container software that is not compatible with Cgroup v2, you can use a systemd override configuration (drop-in) to resolve the issue.

Principle: Instead of relying on a potentially ineffective global configuration, this solution configures systemd to use a specified swappiness value when creating the core slices.

Procedure:

  1. Create an override configuration for system.slice (affects all system services):

    Replace 60 with your desired swappiness value.

    sudo mkdir -p /etc/systemd/system/system.slice.d/
    sudo tee /etc/systemd/system/system.slice.d/99-swappiness.conf <<'EOF'
    [Slice]
    MemorySwappiness=60
    EOF
  2. Create an override configuration for user.slice (affects all user logon sessions).

    Replace 60 with your desired swappiness value.

    sudo mkdir -p /etc/systemd/system/user.slice.d/
    sudo tee /etc/systemd/system/user.slice.d/99-swappiness.conf <<'EOF'
    [Slice]
    MemorySwappiness=60
    EOF
  3. Restart to apply the configuration.

    sudo systemctl daemon-reload
    sudo reboot
    daemon-reload only reloads the systemd configuration. To ensure that all services and sessions are created under the new slice configuration, you must restart the server.