Create and Add Swap On Linux OS CentOS/Ubuntu/Debian CWP Centos WebPanel and VestaCP
In this Article we’re going to add Swap space to Linux OS (RHEL, CentOS, Ubuntu) to prevent memory full issues. Swap is important when your server frequently going out of memory and got hanged (OOM) this can cause MySQL database corruption and many issues with the server. Before we get started I like to inform that this tutorial is only valid for KVM type servers and Dedicated servers. For Openvz and other container based servers this tutorial will not work.
Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory.
- Protection against OOM (out of memory) errors, crashes, memory-related system unpredictability/instability.
- Increases available memory to the system and allows more programs to be run concurrently & more safely
- Prevent server non responsiveness/ hangs
Step 1 :
Follow this commands one by one :
cd /var touch swap.img chmod 600 swap.img
STEP 2 :
We’ll create 1GB (1024MB) of Swap :
dd if=/dev/zero of=/var/swap.img bs=1024k count=1000
if you want to create 2 gb swap increase the “count” value to “2000” for 3gb increase “count” to : “3000”
###############
2gb eg. :
dd if=/dev/zero of=/var/swap.img bs=1024k count=2000
3gb eg. :
dd if=/dev/zero of=/var/swap.img bs=1024k count=3000
###############
result will look like this :
[root@srv1 var]# dd if=/dev/zero of=/var/swap.img bs=1024k count=1000 1000+0 records in 1000+0 records out 1048576000 bytes (1.0 GB) copied, 3.30777 s, 317 MB/s
STEP 3 :
Creating swap img file :
mkswap /var/swap.img
result will look like this :
[root@srv1 var]# mkswap /var/swap.img Setting up swapspace version 1, size = 1023996 KiB no label, UUID=5813e8e7-1034-4700-84c2-c06905e26535
STEP 4 :
Enabling Swap :
swapon /var/swap.img
Checking Swap :
free -h
[root@srv1 var]# free -h total used free shared buff/cache available Mem: 1.9G 260M 144M 27M 1.6G 1.5G Swap: 999M 0B 999M
Step 5 :
making it Enable during server boot, run the below command which will add entry in /etc/fstab :
echo "/var/swap.img none swap sw 0 0" >> /etc/fstab
All done, you just enabled Swap partition on your server. let me know how it goes as i tried to make the tutorial as simple as could be.
TO create/modify/delete existing swap first off the swap :
Swap Off :
swapoff -a
Then delete the swap file :
rm -rf /var/swap.img
After deleting follow the STEPs above from very first (Skip Step 5 if already executed this command before) .