Cyberithub

How to Add the Swap Space in Linux (RedHat/CentOS 7/8) Using Best Methods

Advertisements

In this article, we will look into the steps to add the swap space in Linux (RedHat/CentOS 7/8). swap is an important feature in Linux Based Systems which is required when we do not have enough space of main memory. This can be understand from a simple example where let's say you have 2GB of RAM in your system and suddenly a process requires 3GB from memory but system does not have this much memory so in that case memory will be allocated from Swap if it is available in your system.

If swap memory was not allocated then probably your system will crash due to memory Leak. Hence swap plays a critical role in Memory allocation. In this section, we will different ways to add swap space in Linux.

How to Add the Swap Space in Linux (RedHat/CentOS 7/8) Using Best Methods 1

Add the Swap Space in Linux

There are different ways through which one can add swap space in his system. You can either do it through by adding through disk partition which is also a recommended way or you can do it through by adding a file as swap. In disk partition you can either use entire disk or you can use a part of disk by creating multiple partitions on the disk and using only a single partition. You can also the LVM disk to add a swap partition.

Here we will try to see the number of ways one can add swap memory in Linux and will also see how to remove them.

NOTE:

Please note that here I am using root user to run all the below commands. You can use any user with sudo access to run all these commands. For more information Please check Step by Step: How to Add User to Sudoers to provide sudo access to User.

1. Add Disk swap space in Linux

Also Read: 25 Useful Linux SS Command Examples to Monitor Network Connections

a)Create a swap partition

First you need to create a partition over the disk /dev/sdb using fdisk /dev/sdb command as shown below.

[root@localhost ~]# fdisk -c /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): n
Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-16777215, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-16777215, default 16777215):
Using default value 16777215
Partition 1 of type Linux and of size 8 GiB is set

After creating a partition in /dev/sdb disk we need to change the partition type to Swap. To change we need to use Command t and List all the Hex codes using L to check the hex code for Swap. As you can see from below output, swap hexcode is 82 so we will give this value to change the /dev/sdb partition to swap and then command w to sync and update the partition information.

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): L

0 Empty             24 NEC DOS            81 Minix / old Lin    bf Solaris
1 FAT12             27 Hidden NTFS Win    82 Linux swap / So    c1 DRDOS/sec (FAT-
2 XENIX root        39 Plan 9             83 Linux              c4 DRDOS/sec (FAT-
3 XENIX usr         3c PartitionMagic     84 OS/2 hidden C:     c6 DRDOS/sec (FAT-
4 FAT16 <32M        40 Venix 80286        85 Linux extended     c7 Syrinx
5 Extended          41 PPC PReP Boot      86 NTFS volume set    da Non-FS data
6 FAT16             42 SFS                87 NTFS volume set    db CP/M / CTOS / .
7 HPFS/NTFS/exFAT   4d QNX4.x             88 Linux plaintext    de Dell Utility
8 AIX               4e QNX4.x 2nd part    8e Linux LVM          df BootIt
9 AIX bootable      4f QNX4.x 3rd part    93 Amoeba             e1 DOS access
a OS/2 Boot Manag   50 OnTrack DM         94 Amoeba BBT         e3 DOS R/O
b W95 FAT32         51 OnTrack DM6 Aux    9f BSD/OS             e4 SpeedStor
c W95 FAT32 (LBA)   52 CP/M               a0 IBM Thinkpad hi    eb BeOS fs
e W95 FAT16 (LBA)   53 OnTrack DM6 Aux    a5 FreeBSD            ee GPT
f W95 Ext'd (LBA)   54 OnTrackDM6         a6 OpenBSD            ef EFI (FAT-12/16/
10 OPUS             55 EZ-Drive           a7 NeXTSTEP           f0 Linux/PA-RISC b
11 Hidden FAT12     56 Golden Bow         a8 Darwin UFS         f1 SpeedStor
12 Compaq diagnost  5c Priam Edisk        a9 NetBSD             f4 SpeedStor
14 Hidden FAT16 <3  61 SpeedStor          ab Darwin boot        f2 DOS secondary
16 Hidden FAT16     63 GNU HURD or Sys    af HFS / HFS+         fb VMware VMFS
17 Hidden HPFS/NTF  64 Novell Netware     b7 BSDI fs            fc VMware VMKCORE
18 AST SmartSleep   65 Novell Netware     b8 BSDI swap          fd Linux raid auto
1b Hidden W95 FAT3  70 DiskSecure Mult    bb Boot Wizard hid    fe LANstep
1c Hidden W95 FAT3  75 PC/IX              be Solaris boot       ff BBT
1e Hidden W95 FAT1  80 swap space in Linux
Hex code (type L to list all codes): 82
Changed type of partition 'Linux' to 'Linux swap / Solaris'

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

b)Create a swap filesystem using mkswap command

Now create a swap filesystem over /dev/sdb1 disk using mkswap /dev/sdb1 command as shown below.

[root@localhost ~]# mkswap /dev/sdb1
Setting up swapspace version 1, size = 8387580 KiB
no label, UUID=21ddf61d-aab0-49eb-ab13-cca39babb4e1

c)Add Swap Partition Entry in /etc/fstab 

Once swap partition is created, we need to add a entry in /etc/fstab file so that swap space in Linux will remain enable even after a System reboot. You need to add the below entry at the end of /etc/fstab file and then save and exit.

[root@localhost ~]# vi /etc/fstab

/dev/sdb1 swap swap defaults 0 0

d)Enable swap space in Linux using swapon command

After adding the swap partition in /etc/fstab file you need to enable it by using swapon -a command. This command will enable all the swap partition in the system.

[root@localhost ~]# swapon -a

All the swap space are now enabled in the System. You can check the stats by using swapon -s command as shown below.

[root@localhost ~]# swapon -s
Filename    Type     Size   Used Priority
/dev/dm-1 partition 2097148   0    -2
/dev/sdb1 partition 8387580   0    -3

2. Remove Disk Swap Space in Linux

Also Read : 8 Useful Linux watch command examples (RedHat/CentOS 7/8)

You can also remove the disk swap partition once you are done with the swap space in Linux.

a) Disable swap using swapoff command

Firstly you need to disable the swap partition using swapoff /dev/sdb1 command as shown below.

[root@localhost ~]# swapoff /dev/sdb1

Check the status again by using swapon -s command to confirm if the swap is disabled or not. This will confirm the swap space in Linux is enabled or not.

[root@localhost ~]# swapon -s
Filename    Type     Size   Used Priority
/dev/dm-1 partition 2097148   0    -2

b) Remove the swap Entry from /etc/fstab

Once it is disabled it can now be safely removed from /etc/fstab file by simply removing the entry or commenting out the Line. This will remove the swap space in Linux.

[root@localhost ~]# cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Thu Apr 23 12:36:31 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=1e70f026-ce6f-4938-a74c-ec9c5f6ce74a /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

c) Delete the Partition

Now you can also delete the disk partition 1 created on /dev/sdb using fdisk command as shown below. Run the fdisk /dev/sdb command and select d to delete the partition. Since there is only one partition in this disk so it will select and delete that partition by itself. Then enter w to sync and re-read the partition table.

[root@localhost ~]# fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): d
Selected partition 1
Partition 1 is deleted

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

Now if you check the /dev/sdb partition by using fdisk -l /dev/sdb command you won't find any partition on this disk. This confirms that partition is deleted successfully.

NOTE:

Please note that this is an optional step to perform in removing the swap partition. If you are planning discontinue the swap disk usage for now and want to use it later then there is no need to delete a partition you can simply follow Step 1 and 2 to disable the swap space in Linux and you should be fine. It all depends on your requirements.

3. Add File Swap Space in Linux

Also Read: How to Enable or Disable SELinux Temporarily or Permanently on RedHat/CentOS 7/8

Sometimes it might happen that you don't have any separate disk to create a swap space in Linux. In that case you can use your current disk usage to add swap memory by simply using a file as swap space in Linux. Below are the steps in detail to achieve this goal.

a) Create a file to use as swap space in Linux

To use the file as swap partition you need to first create a file of certain size using dd command as shown below. Here we are creating a file testswap and filling with zeroes with increase the size up to 512MB.

[root@localhost ~]# touch testswap
[root@localhost ~]# dd if=/dev/zero of=/root/testswap bs=1M count=512
512+0 records in
512+0 records out
536870912 bytes (537 MB) copied, 0.98406 s, 546 MB/s

b) Change permission of the File

It is good idea to provide appropriate permissions in the file before proceeding towards formatting a swap filesystem on it. We will assign 600 permission to secure the file.

[root@localhost ~]# chmod 600 testswap

c) Create a swap filesystem

Now create a swap filesystem over testswap file using mkswap command as shown below.

[root@localhost ~]# mkswap testswap
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=01fd76c6-8775-4b89-beb6-f0b7d90a99f0

d) Provide a Entry in /etc/fstab

You can provide a entry of /root/testswap at the end of /etc/fstab file to permanently enable the swap space.

[root@localhost ~]# cat /etc/fstab

/root/testswap swap swap defaults 0 0

e) Enable swap space in Linux using swapon command

Finally you need to enable swap using swapon -a command as shown below. This will enable swap space in Linux.

[root@localhost ~]# swapon -a

You can now check the summary by swapon -s command as shown below.

[root@localhost ~]# swapon -s
Filename    Type     Size   Used Priority
/dev/dm-1 partition 2097148   0    -2
/root/testswap file 524284 0 -3

4. Remove File Swap Space in Linux

Also Read: 10 Popular Examples of sudo command in Linux(RedHat/CentOS 7/8)

Like you have seen above to remove disk swap partition, you can also remove file swap space in Linux using below steps.

a) Remove entry from /etc/fstab

First you either need to remove or comment out the swap entry or from /etc/fstab file as shown below.

[root@localhost ~]# cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Thu Apr 23 12:36:31 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=1e70f026-ce6f-4938-a74c-ec9c5f6ce74a /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

b) Disable Swap using swapoff command

Then you need to disable the swap using swapoff command as shown below.

[root@localhost ~]# swapoff /root/testswap

Once disabled you can check the swap status again and confirm if the swap entry is indeed removed.

[root@localhost ~]# swapon -s
Filename    Type      Size  Used Priority
/dev/dm-1 partition 2097148   0    -2

c) Delete the File

After removing the swap either you can delete the file or you can keep it for future use based on your requirements.

[root@localhost ~]# rm /root/testswap
rm: remove regular file ‘/root/testswap’? y

5. Add LVM Swap Space in Linux

Also Read: 9 useful w command in Linux with Examples

a)Create a Logical Volume

You need to create a logical volume log_vol from volume group vol_grp.

[root@localhost ~]# lvcreate -l 200 -n log_vol vol_grp
Logical volume "log_vol" created.

b)Create an EXT4 Filesystem using mkfs command

After creating a logical volume you need to now create an ext4 filesystem over it using mkfs command as shown below.

[root@localhost ~]# mkfs -t ext4 /dev/vol_grp/log_vol
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
51296 inodes, 204800 blocks
10240 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=209715200
7 block groups
32768 blocks per group, 32768 fragments per group
7328 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840

Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

c)Create Swap Partition using mkswap command

You can again use the same mkswap command to create swap partition on logical volume log_vol as shown below.

[root@localhost ~]# mkswap /dev/vol_grp/log_vol
mkswap: /dev/vol_grp/log_vol: warning: don't erase bootbits sectors
(dos partition table detected). Use -f to force.
Setting up swapspace version 1, size = 819196 KiB
no label, UUID=e3079fa6-a5f1-4997-b7df-8e1e9a4c33b1

d)Create an Entry in /etc/fstab

Add the entry in /etc/fstab file as shown below.

[root@localhost ~]# vi /etc/fstab

/dev/vol_grp/log_vol swap swap defaults 0 0

e)Enable Swap using swapon command

Now you need to enable the swap space in Linux using swapon -a command and check the status by running swapon -s command as shown below.

[root@localhost ~]# swapon -a
[root@localhost ~]# swapon -s
Filename Type Size Used Priority
/dev/dm-1 partition 2097148 0 -2
/dev/dm-2 partition 819196 0 -3

6. Remove LVM Swap Space in Linux

Also Read: 12 Most Popular rm command in Linux with Examples

a) Disable swap using swapoff command

Same as shown in above examples, first disable the swap using swapoff /dev/vol_grp/log_vol command as shown below.

[root@localhost ~]# swapoff /dev/vol_grp/log_vol

Check swap status using swapon command.

[root@localhost ~]# swapon -s
Filename     Type     Size Used Priority
/dev/dm-1 partition 2097148  0    -2

b) Remove LVM partition entry from /etc/fstab

Then remove the swap partition entry from /etc/fstab file as shown below.

[root@localhost ~]# cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Thu Apr 23 12:36:31 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=1e70f026-ce6f-4938-a74c-ec9c5f6ce74a /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

c)Disable Logical Volume using lvchange command

This step is very important where you need to disable the logical volume first before even try to delete it. Although it is possible to delete the logical volume without disabling it but it will create problem when you want to use the same volume later by re-enabling it. Deleting the active volume without disabling it might corrupt the volume and hence corrupt the data. So it is always recommended to disable the volume first. Below is the command to disable logical volume log_vol.

[root@localhost ~]# lvchange -an /dev/vol_grp/log_vol

Check Logical Volume status using lvscan command.

[root@localhost ~]# lvscan
ACTIVE '/dev/vol_grp/log_vol1' [12.00 MiB] inherit
ACTIVE '/dev/vol_grp/log_grp' [2.00 GiB] inherit
inactive '/dev/vol_grp/log_vol' [800.00 MiB] inherit
ACTIVE '/dev/centos/swap' [2.00 GiB] inherit
ACTIVE '/dev/centos/root' [36.99 GiB] inherit

-an : deactivate the logical volume

d) Delete the LVM Partition using lvdelete command

Finally you can delete the logical volume using lvremove /dev/vol_grp/log_vol command as shown below.

[root@localhost ~]# lvremove /dev/vol_grp/log_vol
Logical volume "log_vol" successfully removed

Check the Volume group utilization again to Confirm if the space is reclaimed or not.

[root@localhost ~]# vgdisplay vol_grp
--- Volume group ---
VG Name vol_grp
System ID
Format lvm2
Metadata Areas 2
Metadata Sequence No 3
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 0
Open LV 0
Max PV 0
Cur PV 2
Act PV 2
VG Size 15.99 GiB
PE Size 4.00 MiB
Total PE 4094
Alloc PE / Size 0 / 0
Free PE / Size 4094 / 15.99 GiB
VG UUID 2W12Cx-zE0Q-r35g-tTE4-3vfp-fzE6-5FBRLD

 

 

Popular Recommendations:-

Create KVM Virtual machine using Cockpit UI RHEL CentOS 7/8

Openssl Tutorial: General and Install Certificate on Apache Server in 8 Easy Steps

How to Install and Use telnet command in Linux(RedHat/CentOS 7/8) Using 5 Easy Steps

Leave a Comment