What is SWAP?
It’s simply a portion of hard disk, which acts like RAM. It’s used when total amount of Physical Memory is full. If the RAM is filled up and the system requires more memory, inactive pages on the memory (RAM) are moved to the SWAP space. Even it acts like physical memory, it’s not a replacement for RAM.
Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap files.
A better equation for SWAP:
SWAP = Physical Memory x 2 ; if the Physical Memory < 2 SWAP = Physical Memory + 2 ; if the Physical Memory > 2
Example:
If RAM = 2 Swap = 2 x 2 = 4 If RAM = 4 (> 2) Swap = 4 + 2 = 6
Here I’m explaining the steps to create Swap space by creating Swap file using dd command and swapon.
Procedures
** dd command is used to create a swap file.
** mkswap command is used to setup a Linux swap area under the system or file.
Step 1: Login as root user.
Step 2: Create a storage file.(using dd command)
dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
Output should be like:
# dd if=/dev/zero of=/swapfile1 bs=1024 count=524288 524288+0 records in 524288+0 records out 536870912 bytes (537 MB) copied, 1.34966 s, 398 MB/s
Command explanation:
1. if=/dev/zero : Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile1.
2. of=/swapfile1 : Read from /dev/zero write stoage file to /swapfile1.
3. bs=1024 : Read and write 1024 BYTES bytes at a time.
4. count=524288 : Copy only 523288 BLOCKS input blocks.
step 3: Setup Linux swap area (using “mkswap” command).
mkswap /swapfile1
setup correct file permission for better security.
chown root.root /swapfile1
chmod 600 /swapfile1
Step 4: Activate the swap file (using swapon command).
swapon /swapfile1
Note : To de-activate swap using the command swapoff
That’s it dude!! 🙂
For permanent setting, add this to /etc/fstab file
vi /etc/fstab
####
/swapfile1 swap swap defaults 0 0
####
Save and close the file! It came automatically after the next reboot of your server. Use “free -m” command to check the SWAP details. Cool… 🙂
Thank you for the shared knowledge, can this solution be applied to
Out of memory: ⚠ The process “mysqld” was terminated because the system is low on memory.
mysqld
Event Time
Thursday, February 11, 2016 8:12:55 PM UTC
Process Username
mysql
Process Total Virtual Memory
1371440kB
Process Anonymous Resident Set Size
96292kB
Process File Resident Set Size
312kB
Process OOM Score
38
Status
Out of Memory ⚠
Memory Information
Used
443 MB
Available
2.96 GB
Installed
3.4 GB
Uptime
36 days, 3 hours, 43 minutes, and 29 seconds
IOStat Information
I’m not sure if the SWAP helps here.
Please make sure that the PHP memory limit and also try removing cached memory. This may help.
If the problem persists, paste here the output of “free -m.”