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.
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.
Log on to the ECS instance.
Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.
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.
Check the swap partition configuration.
swapon --showIf 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.

Step 2: Create and set up the Swap file
Create a swap file.
This example creates a 1 GiB swap file named
/swapfileusing thefallocatecommand. This command allocates file space instantly and is more efficient thandd.# Create a 1 GiB swap file sudo fallocate -l 1G /swapfileIf the file system, such as an early version of XFS, does not support
fallocate, the system returns the messagefallocate failed: Operation not supported. In this case, use theddcommand instead. This command takes longer to run.sudo dd if=/dev/zero of=/swapfile bs=1M count=1024The 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
bsandcountdetermine the size of the swap file. You can customize these values. In this command,bs=1M count=1024sets the swap file size to 1 GB.
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 /swapfileFormat the file as a swap area. This marks the file for use as swap space.
sudo mkswap /swapfileA successful response is 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 must be larger than 40 KB. Otherwise, the
mkswapcommand returns an error.
Step 3: Enable and verify Swap
Activate the swap file and confirm that the system recognizes it.
Activate the swap file.
sudo swapon /swapfileVerify that the swap file is enabled.
swapon --showAfter this is successfully enabled, the following appears:
NAME TYPE SIZE USED PRIO /swapfile file 1G 0B -2Alternatively, you can run the
free -hcommand to check the swap status. TheSwaprow 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.
(Recommended) Back up the
fstabfile to prevent issues that may arise from incorrect operations.sudo cp /etc/fstab /etc/fstab.bak.$(date +%Y%m%d)Append the swap configuration to the
fstabfile.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." fiVerify 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 based on the fstab content. 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.
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.
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 | 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:
Edit the
/etc/sysctl.conffile. 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=10Save and exit the file. Then, run the following command to apply the configuration.
sudo sysctl -pRun the following command to verify that the
swappinessparameter configuration is effective.cat /proc/sys/vm/swappinessOutput similar to the following indicates that the
swappinessparameter configuration is effective.
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) |
| Focus on the |
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 |
|
|
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.
Disable the specified swap file.
sudo swapoff /swapfileRemove the automatic mount configuration from
/etc/fstab. You can use thesedcommand to safely delete the corresponding line and avoid manual editing errors.sudo sed -i '\|/swapfile|d' /etc/fstabDelete the swap file to release disk space.
sudo rm /swapfileVerify that the swap file is completely disabled.
Run the
swapon --showorfree -hcommand and confirm that the swap information is no longer displayed.
Disable a swap partition
Run the following command to disable the swap partition.
sudo swapoff /swapfileNoteThe
/swapfileparameter specifies the swap partition identifier. Replace it with the actual identifier from your environment.Edit the
/etc/fstabfile and delete the swap mount information, such as the following entry, to disable automatic mounting./swapfile none swap defaults 0 0Save and close the file. Then, run the following command to check if the swap partition is disabled.
swapon --showIf the command output is empty, the swap partition is disabled.

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.
Local Cgroup rules: In the default Cgroup v1 mode,
systemdcreates separate Cgroups for system services (system.slice), user sessions (user.slice), and other components. Each Cgroup can have its own resource control parameters, includingmemory.swappiness.Local settings override global settings: When
systemdinitializes these Cgroups, it assigns them a defaultmemory.swappinessvalue, which is usually 60. This Cgroup-specific setting has a higher priority than the globalvm.swappinesssetting that you configure in/etc/sysctl.conf.Result: Running programs follow the
swappinessrule of their Cgroup, not the global rule. This makes the global configuration ineffective.
Quick verification
Find the process ID (PID) of a running process. For example, you can run the
pidof nginxcommand.Check the Cgroup to which the process belongs:
cat /proc/[PID]/cgroupThe output displays a path similar to
/system.slice/nginx.service.Check the actual
swappinessvalue for this Cgroup:cat /sys/fs/cgroup/memory/system.slice/nginx.service/memory.swappinessThe output is most likely
60, even if you set the globalvm.swappinessparameter 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:
Update the kernel boot parameters.
Use thegrubbytool to add thesystemd.unified_cgroup_hierarchy=1parameter 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.
Restart the ECS instance.
This is a kernel-level parameter and requires a restart to take effect.sudo rebootVerify and configure:
Verify: After the instance restarts, run the
mount | grep cgroupcommand. If you see a mount point with the typecgroup2, you have successfully switched to Cgroup v2.Configure: In the
/etc/sysctl.conffile, set the desiredvm.swappinessvalue and run thesudo sysctl -pcommand 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:
Create an override configuration for
system.slice(affects all system services):Replace
60with your 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 EOFCreate an override configuration for
user.slice(affects all user logon sessions).Replace
60with your 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 EOFRestart to 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.