Linux - Adding a swap file to RHEL

It is very possible that you may want to increase swap space after installation. For myself, my server is running out of memory, both physical and virtual. So as a workaround, I tried the following to increase my swap space. Although swap partition is recommended, I chose swap file because it will be less disruptive to the users (ie, do not need to reboot..)

To add a swap file:

Determine the size of the new swap file in megabytes and multiple by 1024 to determine the block size. For example, the block size of a 8GB swap file is 8192000.

1. At a shell prompt as root, type the following command with count being equal to the desired block size:

dd if=/dev/zero of=/swapfile bs=1024 count=8192000

The command output is

$ dd if=/dev/zero of=/swapfile bs=1024 count=8192000
8192000+0 records in
8192000+0 records out
8388608000 bytes (8.4 GB) copied, 25.3272 s, 331 MB/s

2. Setup the swap file with the command:

mkswap /swapfile

The command output is

$ mkswap /swapfile
mkswap: /swapfile: warning: don't erase bootbits sectors
        on whole disk. Use -f to force.
Setting up swapspace version 1, size = 8191996 KiB
no label, UUID=7s1166af-ls99-e938-lpos-p0a9000e1234


3. To enable the swap file immediately but not automatically at boot time:

swapon /swapfile

This command does not have any output

4. To enable it at boot time, edit /etc/fstab to include:

/swapfile               swap                    swap    defaults        0 0

The next time the system boots, it enables the new swap file.

This command does not have any output

5. After adding the new swap file and enabling it, verify it is enabled by viewing the output of the command cat /proc/swaps or free.

You could also use Top or HTop command to see the additional swap amount. Or, you could ls -al / to see the swapfile

$ ls -al /
...
-rw-r--r--    1 root root 8388608000 Jul  5 22:21 swapfile
...

The above is reference from RedHat System Administrator Guide with my own experience added.


Comments

Popular Posts