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.
-
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)
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
Log on to an ECS instance.
Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target instance.
Navigate to the details page of the target instance. Click Connect and select Workbench. Follow the on-screen prompts to access the terminal.
-
Run the following command to enable the swap partition.
acs-plugin-manager --exec --plugin ACS-ECS-SwapConfig --params --enableThe 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.NoteThe 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.swappinessparameter 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.
Log on to an ECS instance.
Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target instance.
Navigate to the details page of the target instance. Click Connect and select Workbench. Follow the on-screen prompts to access the terminal.
-
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.

-
Step 2: Create and set up the swap file
-
Create a swap file.
This example shows how to create a 1 GiB
/swapfile. We recommend that you use thefallocatecommand. It can instantly allocate file space and is much more efficient thandd.# Create a 1 GiB swap file sudo fallocate -l 1G /swapfileIf a file system (such as an early version of XFS) does not support
fallocate, the system returns thefallocate failed: Operation not supportederror. In this case, use theddcommand to create the file instead, but this process takes longer.sudo dd if=/dev/zero of=/swapfile bs=1M count=1024-
The
ofvalue/swapfileis a customizable variable that represents the identifier for the swap partition and cannot be the same as an existing partition identifier. -
The values of
bsandcountdetermine the size of the swap file and can be customized. For example,bs=1M count=1024sets the swap file size to 1 GB.
-
-
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 -
Mark the file as swap space.
sudo mkswap /swapfileA successful response looks similar to the following:
Setting up swapspace version 1, size = 1 GiB (1073737728 bytes) no label, UUID=a1a7e24c-38f6-41a4-9e18-be60b631133aNote: The swap file size must be greater than 40 KB. Otherwise, the
mkswapcommand reports an error.
Step 3: Enable and verify the swap file
Activate the newly created swap file and confirm that the system recognizes it.
-
Activate the swap file.
sudo swapon /swapfile -
Verify that swap is enabled.
swapon --showAfter successful activation, the output is as follows:
NAME TYPE SIZE USED PRIO /swapfile file 1G 0B -2Alternatively, run
free -h. TheSwaprow 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.
-
(Recommended) Back up the
fstabfile to prevent operational errors.sudo cp /etc/fstab /etc/fstab.bak.$(date +%Y%m%d) -
Append the Swap configuration to the
fstabfile.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 -
Verify the persistent configuration.
You can verify that the
/etc/fstabconfiguration 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 --showIf 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.
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 |
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:
-
Edit the
/etc/sysctl.conffile. 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 -
Save the file and exit. Then, run the following command to apply the configuration.
sudo sysctl -p -
Verify that the
swappinessparameter configuration has taken effect.cat /proc/sys/vm/swappinessThe following output indicates that the
swappinessparameter configuration has taken effect.
Monitor swap usage
|
Monitoring purpose |
Recommended command |
Description |
|
View overall memory and swap usage |
|
The most common and straightforward command. |
|
Monitor real-time swap activity (swap-in/swap-out) |
|
Pay attention to the |
|
Find processes that are using swap |
|
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 |
|
|
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.
-
Disable the specified swap file.
sudo swapoff /swapfile -
Remove the auto-mount configuration from
fstab. Use thesedcommand to safely remove the corresponding line and avoid errors from manual editing.sudo sed -i '\|/swapfile|d' /etc/fstab -
Delete the swap file to free up disk space.
sudo rm /swapfile -
Verify that swap is completely disabled.
Run
swapon --showorfree -hto 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.
-
Cgroup-specific rules: In the default Cgroup v1 mode,
systemdcreates 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 asmemory.swappiness. -
Local settings override global settings: When
systemdinitializes these Cgroups, it sets a defaultmemory.swappinessvalue for them (usually 60). This Cgroup-specific setting takes precedence over the globalvm.swappinessconfigured in/etc/sysctl.conf. -
Result: The running program actually follows the
swappinessrule of its Cgroup instead of the global rule, which renders the global configuration ineffective.
Quick verification
-
Find the PID of a running process (for example,
pidof nginx). -
Check the cgroup to which the process belongs:
cat /proc/[PID]/cgroupYou will see a path such as
/system.slice/nginx.service. -
Check the actual
swappinessvalue of this Cgroup:cat /sys/fs/cgroup/memory/system.slice/nginx.service/memory.swappinessYou will likely see that the output is
60even if you have set the globalvm.swappinessto 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:
-
Update kernel boot parameters:
Use thegrubbytool to add thesystemd.unified_cgroup_hierarchy=1parameter 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.
-
Restart the ECS instance:
This setting is a kernel-level parameter and requires a restart to take effect.sudo reboot -
Verify and configure:
-
Verification: After the restart, run
mount | grep cgroup. If you see a mount point of typecgroup2, it indicates that you have successfully switched to cgroup v2. -
Configuration: Set the desired
vm.swappinessvalue in/etc/sysctl.conf, and runsudo sysctl -pto 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:
-
Create an override configuration for
system.slice(this affects all system services):Replace
60with the desiredswappinessvalue.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 -
Create an override configuration for
user.slice(this affects all user login sessions).Replace
60with the desiredswappinessvalue.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 -
Apply the configuration.
sudo systemctl daemon-reload sudo rebootdaemon-reloadonly reloads thesystemdconfiguration. To ensure that all services and sessions are created under the new Slice configuration, you must restart the server.