Operations 5 min read

How to Add a Swap File on Linux and Adjust Swappiness

This guide explains how to create a swap file on a Linux server, enable it, configure it to start at boot, and adjust the swappiness parameter to control virtual memory usage, providing step‑by‑step commands and explanations for each operation.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
How to Add a Swap File on Linux and Adjust Swappiness

If your server constantly reports out‑of‑memory errors and services are being killed, enabling a swap area is a practical way to add virtual memory without purchasing additional RAM.

In this example, a 1‑CPU 1‑GB Alibaba Cloud ECS instance runs memory‑intensive software such as the ELK stack, making swap useful.

Typically, setting swap size to twice the physical memory is sufficient; larger sizes only waste disk space.

2. Add a Swap File

Because the disk is already partitioned, we use a file as the swap area. All commands must be run as the root user.

Check current memory usage with free -h ; you will see that physical memory is nearly exhausted and swap is currently a file.

Create a file for swap (e.g., 2 GB):

dd if=/dev/zero of=/root/swapfile2 bs=1M count=2048

Set proper permissions so the swap file is secure:

chmod 0600 /root/swapfile2

Initialize the file as swap space:

mkswap /root/swapfile2

Enable the swap file immediately:

swapon /root/swapfile2

After enabling, you can see that the virtual memory increases by the swap size.

To make the swap file activate on boot, edit /etc/fstab and add the line:

/root/swapfile2 swap swap defaults 0 0

3. Adjust Swap Usage Priority

If you have enough RAM, you may want Linux to use swap less aggressively by changing the swappiness value.

A swappiness of 0 tells the kernel to prefer physical memory as much as possible, while 100 forces aggressive swapping.

Check the current value:

cat /proc/sys/vm/swappiness

Temporarily set it to 60 (effective until reboot):

sudo sysctl vm.swappiness=60

To make the change permanent, edit /etc/sysctl.conf , add or modify the line:

vm.swappiness = 60

Save the file and the new setting will persist after a reboot.

linuxVirtual MemorySystem Administrationswapswappiness
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.