A swap partition in Linux is a designated space on the hard disk that acts as an extension of the system's physical memory (RAM). When the RAM is fully utilized, inactive memory pages are moved to the swap partition, ensuring that processes continue to run smoothly. Swap is particularly beneficial for systems with limited RAM or for memory-intensive tasks.
Unlike a swap file, a swap partition offers more reliable and efficient performance since it communicates directly with the kernel. On servers and systems with significant workloads, it is recommended to set up a dedicated swap partition to optimize performance. The amount of swap space typically depends on the system’s RAM and workload requirements.
Before creating a swap partition, ensure that there is available space on the disk or identify an unused partition. Use commands like lsblk to inspect the current partition layout. Adjusting partitions without caution can result in data loss, so backing up critical data is advised. Once the swap partition is set up, it is essential to configure it properly to activate it during system boot.
Steps to create and add a swap partition in Linux:
- Use the command lsblk to view available partitions.
$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 238.5G 0 disk ├─sda1 8:1 0 200M 0 part /boot/efi ├─sda2 8:2 0 238.3G 0 part /
Identify an available or unused partition where you want to create the swap partition.
- Format the selected partition as swap.
$ sudo mkswap /dev/sdX
Replace X with the appropriate partition number. This command formats the partition for swap use.
- Enable the swap partition with the swapon command.
$ sudo swapon /dev/sdX
- Add the swap partition to the fstab file to enable it during boot.
$ echo '/dev/sdX none swap sw 0 0' | sudo tee -a /etc/fstab
- Confirm the swap partition is active by checking /proc/swaps.
$ cat /proc/swaps Filename Type Size Used Priority /dev/sdX partition 2097148 0 -1
- Verify swap usage with the free command.
$ free -h total used free shared buff/cache available Mem: 1.9G 155M 1.2G 8.8M 566M 1.6G Swap: 2.0G 0B 2.0G
Ensure that the Swap line reflects the correct size and usage.
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.