All Products
Search
Document Center

:Configure a swap partition for a Linux instance

Last Updated:Jun 21, 2026

When an Alibaba Cloud ECS instance runs low on physical memory, configuring swap space is a cost-effective emergency solution. It uses disk space as virtual memory to prevent out-of-memory (OOM) errors and keep the system running when physical memory is exhausted.

Important
  • If an ECS instance is low on memory, we recommend first increasing the physical memory by changing the instance type.

  • We do not recommend using a swap partition on a basic disk because its low I/O performance can cause system bottlenecks. For other types of cloud disks, you can use a swap partition based on your needs. However, you must configure it properly to avoid frequent swapping and maintain system stability.

Method 1: Use the Cloud Assistant plugin (recommended)

Important

To automatically configure a swap partition, you must install the Cloud Assistant Agent. If your instance does not support Cloud Assistant or you cannot install the agent, use Method 2 to configure swap manually.

Enable the swap partition

  1. Log on to an ECS instance.

    1. Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target instance.

    2. Navigate to the details page of the target instance. Click Connect and select Workbench. Follow the on-screen prompts to access the terminal.

  2. Run the following command to enable the swap partition.

    acs-plugin-manager --exec --plugin ACS-ECS-SwapConfig --params  --enable

    The following output indicates that the swap partition is successfully enabled.

    [INFO] The system support auto config swap partition.
    [INFO] Alibaba Cloud Swap Configuration Document:https://www.alibabacloud.com/help/en/ecs/support/how-do-i-configure-the-swap-partition-of-a-linux-instance
    [INFO] Turn On Swap......
    [INFO] RAM size: 8 G
    [INFO] Swap size: 8 G
    [INFO] Check disk available size......
    [INFO] Disk available size: 33 G
    [INFO] Disk available size enough
    [INFO] Recover swap configuration from /etc/fstab
    [INFO] Config vm.swappiness=20 to /etc/sysctl.conf
    [SUCCESS] Swap has been turned on.
    Note

    The plugin automatically sets the swap partition size based on the system memory according to the following rules:

    • If RAM ≤ 2 GB, then Swap Size = RAM × 2.

    • If 2 GB < RAM ≤ 8 GB, then Swap Size = RAM.

    • If RAM > 8 GB, a swap partition is not recommended.

    • A swap partition is not recommended if it would leave less than 5 GB of available disk space.

    The default value of the vm.swappiness parameter is 20. To customize the swap partition size, see Method 2: Manually configure a swap partition.

Check the swap partition status

Run the following command to check the status of the swap partition.

acs-plugin-manager --exec --plugin ACS-ECS-SwapConfig --params  --status

The following output indicates that the swap partition is enabled.

[INFO] The system support auto config swap partition.
[INFO] Alibaba Cloud Swap Configuration Document:https://www.alibabacloud.com/help/en/ecs/support/how-do-i-configure-the-swap-partition-of-a-linux-instance
[INFO] ========== Swap status ==========
NAME      TYPE SIZE USED PRIO
/swapfile file   8G   0B   -2
[INFO] Swap is enabled

Disable the swap partition

Run the following command to disable the swap partition.

acs-plugin-manager --exec --plugin ACS-ECS-SwapConfig --params  --disable

The following output indicates that the swap partition is successfully disabled.

[INFO] The system support auto config swap partition.
[INFO] Alibaba Cloud Swap Configuration Document:https://www.alibabacloud.com/help/en/ecs/support/how-do-i-configure-the-swap-partition-of-a-linux-instance
[INFO] Turn Off Swap......
[INFO] Cancel swap configuration from /etc/fstab
[INFO] Config vm.swappiness=0 to /etc/sysctl.conf
[INFO] Deleted swapfile: /swapfile
[SUCCESS] Swap has been turned off.

Method 2: Manual configuration

Enable the swap partition

Step 1: Check current swap status

Before you begin, verify that your system has no existing swap configuration to avoid conflicts.

  1. Log on to an ECS instance.

    1. Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target instance.

    2. Navigate to the details page of the target instance. Click Connect and select Workbench. Follow the on-screen prompts to access the terminal.

  2. Check the swap partition configuration.

    swapon --show
    • If the command returns no output, no swap is configured and you can proceed to the next step.

    • If output similar to the following is returned, active swap space already exists. You can either disable and clean up the swap file or create a new swap file on a different disk.

      image

Step 2: Create and set up the swap file

  1. Create a swap file.

    This example shows how to create a 1 GiB /swapfile. We recommend that you use the fallocate command. It can instantly allocate file space and is much more efficient than dd.

    # Create a 1 GiB swap file
    sudo fallocate -l 1G /swapfile
    If a file system (such as an early version of XFS) does not support fallocate, the system returns the fallocate failed: Operation not supported error. In this case, use the dd command to create the file instead, but this process takes longer.
    sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
    • The of value /swapfile is a customizable variable that represents the identifier for the swap partition and cannot be the same as an existing partition identifier.

    • The values of bs and count determine the size of the swap file and can be customized. For example, bs=1M count=1024 sets the swap file size to 1 GB.

  2. Set secure permissions.

    To prevent non-root users from reading the swap file, which may contain sensitive data such as passwords and keys, set its permissions to 600.

    sudo chmod 600 /swapfile
  3. Mark the file as swap space.

    sudo mkswap /swapfile

    A successful response looks 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 size must be greater than 40 KB. Otherwise, the mkswap command reports an error.

Step 3: Enable and verify the swap file

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

  1. Activate the swap file.

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

    swapon --show

    After successful activation, the output is as follows:

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

    Alternatively, run free -h. The Swap row should display the total size.

Step 4: Ensure persistence

Write the Swap configuration to the /etc/fstab file to ensure that Swap remains effective after the instance restarts.

  1. (Recommended) Back up the fstab file to prevent operational errors.

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

    The following command checks for an existing swap entry before adding a new one to prevent duplicates.
    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 partitions based on the /etc/fstab file.
    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.

Adjust swappiness

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

  • Higher value: The kernel uses swap more aggressively, moving inactive memory pages to disk sooner.

  • Lower value: The kernel avoids using swap, preferring to keep pages in physical memory, using swap only when physical memory is critically low.

Important

Adjusting swap parameters requires caution. Improper changes can degrade system performance or cause unexpected virtual memory behavior. Make changes only when your specific workload requires it and you fully understand the parameter's function. If unsure, keep the default configuration.

Scenario-based recommendations:

Application scenario

Recommended swappiness value

Rationale

Databases (MySQL, PostgreSQL)

1–10

To ensure query performance, avoid swapping out their core buffer pools.

In-memory databases (Redis, Memcached)

1

In-memory databases are extremely sensitive to latency. Any swap activity can severely degrade 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 by allowing non-core, inactive process pages to be swapped out.

Default/General/Batch workloads

60 (system default)

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

Procedure:

  1. Edit the /etc/sysctl.conf file. For example, to use the swap partition only when physical memory is less than 10%, you need to adjust the following parameter values.

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

    sudo sysctl -p
  3. Verify that the swappiness parameter configuration has taken effect.

    cat /proc/sys/vm/swappiness

    The following output indicates that the swappiness parameter configuration has taken effect.

    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

Pay attention to the si (swap-in) and so (swap-out) columns. If these two columns show non-zero values over an extended period, it indicates that the system is frequently performing swap operations and may have a performance issue.

Find processes that are using swap

for file in /proc/*/status; do awk '/Name:/{n=$2} /VmSwap:/{s=$2} END{if(s>0) printf "%-20s %s\n", n, s"kB"}' $file; done | sort -k2 -hr

This command iterates through all processes, lists each process's name and swap usage, and then sorts the results to show the processes with the highest swap usage at the top.

Analyze historical performance

atop

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

Disable and clean up swap

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

  1. Disable the specified swap file.

    sudo swapoff /swapfile
  2. Remove the auto-mount configuration from fstab. Use the sed command to safely remove the corresponding line and avoid errors from manual editing.

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

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

    Run swapon --show or free -h to confirm that the swap information has disappeared.

FAQ

Why doesn't swap work as expected?

After creating a swap partition and adjusting the swappiness parameter, you may notice a confusing phenomenon: even when physical memory is under high pressure, swap partition usage remains low, which may make it seem as if the swappiness setting has not taken effect.

Problem diagnosis

The root cause of this problem lies in the systemd and control group (Cgroup) mechanisms widely used in modern Linux distributions.

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

  2. Local settings override global settings: When systemd initializes these Cgroups, it sets a default memory.swappiness value for them (usually 60). This Cgroup-specific setting takes precedence over the global vm.swappiness configured in /etc/sysctl.conf.

  3. Result: The running program actually follows the swappiness rule of its Cgroup instead of the global rule, which renders the global configuration ineffective.

Quick verification
  1. Find the PID of a running process (for example, pidof nginx).

  2. Check the cgroup to which the process belongs:

    cat /proc/[PID]/cgroup

    You will see a path such as /system.slice/nginx.service.

  3. Check the actual swappiness value of this Cgroup:

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

    You will likely see that the output is 60 even if you have set the global vm.swappiness to another value. This indicates that the global configuration is not taking effect.

Solutions

Solution 1: Switch to cgroup v2 (recommended)

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

Procedure:

  1. Update kernel boot parameters:
    Use the grubby tool to add the systemd.unified_cgroup_hierarchy=1 parameter to 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 GRUB boot configuration, so the system will initialize in cgroup v2 mode on the next startup.
  2. Restart the ECS instance:
    This setting is a kernel-level parameter and requires a restart to take effect.



    sudo reboot
  3. Verify and configure:

    • Verification: After the restart, run mount | grep cgroup. If you see a mount point of type cgroup2, it indicates that you have successfully switched to cgroup v2.

    • Configuration: Set the desired vm.swappiness value in /etc/sysctl.conf, and run sudo sysctl -p to apply the setting to the entire system.

Solution 2: Configure persistence in cgroup v1 (alternative)

If your environment cannot be switched for specific reasons (for example, it runs older container software that is incompatible with cgroup v2), you can use a systemd drop-in configuration to resolve the issue.

Principle: This method no longer relies on potentially faulty global configurations. Instead, it directly instructs systemd to use the specified swappiness value when creating the core slice.

Procedure:

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

    Replace 60 with the 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 (this affects all user login sessions).

    Replace 60 with the 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. 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.