Swap Linux Memory to Increase Virtual RAM for VPS: Detailed A-Z Instructions

Swap Memory Linux Tăng RAM Ảo Cho VPS: Hướng Dẫn Chi Tiết A-Z

Have you ever had to face-to-face restarting a VPS that was running smoothly just because of a damn "Out of Memory" (OOM) error? It happened to me, right when the traffic was pouring in the highest it hurt. Setting up Linux swap memory to increase virtual RAM for VPS is a real savior in those suffocating moments. It is not a magic pill that helps the server run twice as fast, but it is certainly an extremely effective "fire extinguisher", making your VPS more stable, not crashing when the physical RAM is suddenly overloaded. Let's dive into the details of how to set up and optimize it right now.

What is Swap that is so "divine"? When do you really need it?

Swap memory is essentially an area of ​​space on a hard drive (usually an SSD) used by the Linux operating system as auxiliary RAM when the physical RAM capacity is exhausted, helping to keep the system from freezing.

What is swap memory? Savior or just a temporary solution?

Swap memory là gì? Đây là kỹ thuật quản lý bộ nhớ Linux cho phép chuyển các dữ liệu ít được sử dụng từ RAM vật lý sang một không gian lưu trữ trên ổ cứng (gọi là file swap hoặc phân vùng swap). Khi hệ thống cần lại các dữ liệu đó, kernel sẽ hoán đổi chúng ngược trở lại RAM.

At Pham Hai, during many years of operating servers, I have always considered swap an extremely important situational solution. When your application (like MySQL or PHP) suddenly consumes too much RAM, instead of the kernel activating the OOM Killer mechanism to kill the website, it will push old data into the swap cache. This helps the system buy time and maintain life so you can promptly intervene. However, it cannot replace real RAM because the drive read and write speed is thousands of times slower than RAM.

Benefits and disadvantages of using virtual RAM

The biggest benefit of virtual RAM is preventing application crashes due to lack of RAM and increasing overall server stability. The downside is that if abused, the system will become very slow due to "throshing" (continuous reading and writing of the hard drive).

Lợi ích và nhược điểm của swap memory có thể tóm tắt như sau:

  • Lợi ích: Tránh lỗi out of memory (OOM), cho phép chạy các ứng dụng yêu cầu bộ nhớ lớn hơn RAM thực tế (như khi compile phần mềm), và hỗ trợ tính năng ngủ đông (hibernate) trên các máy trạm Linux.
  • Nhược điểm: Làm giảm tuổi thọ của ổ cứng SSD (dù SSD hiện nay đã rất bền), và có thể làm giảm hiệu suất VPS nghiêm trọng nếu hệ thống liên tục phải hoán đổi dữ liệu. Với những ai đang tìm hiểu về Shared hosting vs VPS vs Dedicated khác gì, bạn sẽ nhận ra rằng trên môi trường VPS, bạn có toàn quyền (và trách nhiệm) phải tự tay cấu hình các thông số tài nguyên hệ thống này để bảo vệ máy chủ của mình.

Bloody experience: When to use and not to use Swap

when should you use swap on VPS? The answer is that it is almost always a good idea to have a little swap as insurance, especially on low-spec VPS plans under 2GB of RAM.

I recommend using swap when:

  • Using VPS packages with limited RAM (1GB - 2GB). For those who are looking for the best cheap VPS packages for WordPress 2026, creating a swap file immediately after purchase is a must to prevent the website from crashing.
  • Occasionally there are short-term traffic spikes that cause RAM to fill up.
  • Cần chạy các lệnh tốn nhiều RAM tạm thời như composer update hay npm install.

You should not use (or use very little) when:

  • Your VPS is running large database servers (such as Elasticsearch, MongoDB) that have strict requirements on actual read and write speed to RAM.
  • You have an excessive amount of physical RAM (e.g. 32GB of RAM for a small website).

Instructions for creating and activating 2GB Swap on Ubuntu/CentOS in 5 minutes

To create a swap file, you simply use the Linux command line over SSH to create an empty file, format it as swap, give it security permissions, and enable it on the system.

For developers, getting familiar with administrative command lines is essential. If you are unfamiliar, you can refer to the article about Basic Linux server administration for developers to master SSH operations before starting. Below is a detailed step-by-step guide to increasing virtual RAM for Linux VPS that works well for both Ubuntu and CentOS.

Step 1: Check if the VPS has Swap with the free -h command

Để biết kiểm tra swap trên Linux bằng lệnh gì, bạn chỉ cần gõ lệnh free -h hoặc swapon --show vào terminal để xem trạng thái bộ nhớ hiện tại.

Open a terminal to connect SSH to your VPS and type:

sudo free -h

Bạn sẽ thấy các cột hiển thị Mem (RAM vật lý) và Swap. Nếu dòng Swap hiện toàn số 0, tức là VPS của bạn chưa có RAM ảo. Bạn cũng có thể dùng lệnh sudo swapon --show. Nếu không có output nào trả về, hệ thống của bạn hoàn toàn trắng swap.

Step 2: Create a 2GB swap file with the command fallocate (fast) or dd (firm)

Cách tạo swap file trên Linux phổ biến nhất là dùng lệnh fallocate để cắt nhanh một khoảng dung lượng ổ đĩa trống, hoặc dùng lệnh dd nếu hệ thống file không hỗ trợ fallocate.

Tính đến năm 2026, hầu hết các VPS đều dùng ổ cứng SSD/NVMe với hệ thống file ext4 hoặc xfs, nên lệnh fallocate hoạt động rất mượt. Để tạo file 2GB, bạn chạy:

sudo fallocate -l 2G /swapfile

If the above command gives an error (common on some older virtualization platforms), switch to dd command. It's a bit slower but definitely successful:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Lệnh này sẽ ghi các byte 0 vào /swapfile cho đến khi đủ 2048 MB (tương đương 2GB).

Step 3: Configure secure access rights for swap files

Bạn bắt buộc phải giới hạn quyền truy cập cho file swap chỉ dành cho user root bằng lệnh chmod 600 để tránh rủi ro rò rỉ dữ liệu nhạy cảm lưu trong RAM ảo.

This is an extremely important security step during configuring swap on Ubuntu or CentOS. If someone can read this file, they can get passwords or running sessions. Run the following command:

sudo chmod 600 /swapfile

Lúc này, chỉ có quyền root mới có thể đọc và ghi vào tệp /swapfile.

Step 4: Activate the swap file with mkswap and swapon commands

In order for the system to recognize the file you just created as a swap, you need to format it with the mkswap command and then enable it with the swap command.

Implement file format:

sudo mkswap /swapfile

Then enable virtual RAM immediately:

sudo swapon /swapfile

Đến đây, việc tăng RAM ảo cho VPS Ubuntu hoặc CentOS của bạn đã hoàn tất tạm thời. Bạn có thể gõ lại free -h để tận hưởng thành quả, cột Swap lúc này đã hiện dung lượng 2GB. Quá trình tạo swap partition trên CentOS hay Ubuntu bằng file thực chất đều mang lại hiệu quả tương đương nhau trên các hệ thống hiện đại.

Step 5: Configure Swap to automatically re-enable when rebooting VPS (important!)

Để file swap tự động được nạp lại mỗi khi khởi động lại máy chủ, bạn phải khai báo đường dẫn của nó vào tệp cấu hình /etc/fstab.

If you skip this step, after restarting the VPS, all your efforts to create the swap will disappear. When you do Configure Ubuntu VPS to run WordPress from scratch, this is always an action I emphasize to do right away. Run the following command to automatically add configuration:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Lệnh này sẽ chèn thêm một dòng vào cuối file /etc/fstab, báo cho kernel biết cần mount /swapfile dưới dạng phân vùng swap mỗi khi boot.

Optimal configuration Swap - Don't just create it!

Để tối ưu hóa swap memory Linux, bạn cần tinh chỉnh các thông số kernel như vm.swappinessvfs_cache_pressure để kiểm soát tần suất hệ thống ghi dữ liệu ra ổ cứng.

What is Swappiness? Adjust it to 10 or keep it 60?

Swappiness là gì và cách cài đặt? Swappiness là một tham số kernel từ 0 đến 100 quyết định mức độ "hung hăng" của Linux trong việc chuyển dữ liệu từ RAM sang Swap; giá trị càng thấp, hệ thống càng cố gắng giữ dữ liệu trong RAM vật lý càng lâu càng tốt.

By default on Ubuntu/CentOS, swappiness is usually at 60. This level is suitable for personal computers but is a disaster for VPS running the web. If you want to increase the speed of your WordPress website, keeping the swappiness high will cause Linux to continuously push PHP/MySQL processes to the hard drive, making the website respond extremely slowly.

Tại Phạm Hải, chúng mình luôn khuyên khách hàng thiết lập vm.swappiness về mức 10 hoặc 20 cho máy chủ web. Ngoài ra, thông số vfs_cache_pressure (mặc định 100) cũng nên giảm xuống 50 để kernel ưu tiên giữ lại các thông tin thư mục (inode/dentry cache) trong bộ nhớ. Cách cấu hình như sau:

sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50

Để lưu vĩnh viễn, bạn mở file /etc/sysctl.conf và thêm 2 dòng:

vm.swappiness=10
vm.vfs_cache_pressure=50

How much Swap capacity is enough for your VPS?

Dung lượng swap bao nhiêu là đủ cho Linux phụ thuộc vào lượng RAM vật lý hiện có; quy tắc chung là RAM dưới 2GB thì Swap gấp đôi RAM, RAM trên 2GB thì Swap bằng RAM cộng thêm 2GB.

There is no absolute number, but based on the latest technical documents in 2026, here is an optimal table of recommendations you can refer to:

Physical RAM capacity Recommended Swap capacity Do you use Hibernate?
Under 2 GB Double the RAM (Example: 1GB RAM -> Swap 2GB) Not important
From 2 GB to 8 GB By actual RAM Swap = RAM + 2GB
From 8 GB to 64 GB Minimum 4 GB Swap = RAM + 2GB

When you Set up your own VPS to run multiple websites on the same server, carefully calculating the amount of RAM and Swap is a vital factor to ensure the websites do not "compete" for resources, leading to the entire system crashing.

How to change or completely delete swap files when no longer needed

Để thực hiện cách xóa swap file trên Linux, bạn cần tắt nó đi bằng lệnh swapoff, xóa khai báo trong fstab và cuối cùng là xóa tệp tin vật lý trên ổ cứng.

Sometimes you upgrade to a huge VPS package with 32GB of RAM and want the system to run 100% on physical memory for maximum speed. Eliminating swap at this time is also a way to force the system to process faster. Especially when you are focusing on Optimizing website for wordpress on vps, the read and write latency from the hard drive even if it is NVMe cannot be compared to RAM. Steps to completely remove:

  1. Tắt swap đang chạy: sudo swapoff -v /swapfile
  2. Mở file /etc/fstab bằng nano và xóa dòng /swapfile none swap sw 0 0.
  3. Xóa file vật lý để giải phóng ổ cứng: sudo rm -f /swapfile

So you already have a way to "pump" more virtual RAM into your Linux VPS. Remember, setting up Linux memory swap to increase VPS virtual RAM is a great defense against OOM errors and keeping the server stable. However, it cannot completely replace the power of physical RAM. Don't abuse it, think of it as a lifesaver in stormy times. If you check and see that your VPS is constantly using swap cache at a high level, that is a cosmic signal reminding you that you need to spend money to upgrade your RAM.

If you find this tutorial useful, please share it with your friends and colleagues! If you have any questions or experiences about memory management that you want to share, don't hesitate to leave a comment below, Pham Hai will respond as soon as possible!

Note: The information in this article is for reference only. For the best advice, please contact us directly for specific advice based on your actual needs.

Categories: Hosting & VPS VPS & Cloud

mrhai

Để lại bình luận