What is Swap?
- Swap is disk space used as virtual memory when RAM is under memory pressure.
- Linux can move less-active memory pages from RAM to swap, freeing RAM for active processes.
- Swap is slower than RAM because it uses disk storage.
- Swap can be created using a disk partition or a file.
Commands
- dd – Creates a swap file with a specified size.
- mkswap – Formats a file or partition for swap use.
- swapon – Activates swap.
- swapoff – Deactivates swap.
- free – Displays RAM and swap usage.
Implementation: Create Swap File
-
Check current memory and swap
Shows total, used, and available RAM and swap.
free -h
-
Create a 1 GB swap file
dd if=/dev/zero of=/docker_swap bs=1M count=1024
- if=/dev/zero – uses zero-filled data as input
- of=/docker_swap – creates the swap file at /docker_swap
- bs=1M – sets the block size to 1 MB
- count=1024 – creates a file of 1024 blocks (1 GB)
Additional Notes: Why not use
touch?-
touchcreates an empty file (or updates its timestamp). -
Swap needs allocated storage, which is why we use
ddor another suitable allocation method.
-
Verify the file
ls -lh /docker_swap
-
Set secure permissions
chmod 600 /docker_swap
- Allows only the root user to read and write the swap file.
- This is the recommended permission setting.
-
Format the file as swap
mkswap /docker_swap
Prepares the file for use as swap space.
-
Check current swap
free -h
The new swap is not active yet, so it will not appear as available swap.
-
Activate the swap file
swapon /docker_swap
Activates the swap file for immediate use.
-
Verify the swap is active
free -h
swapon --show
- free -h – shows the updated RAM and swap information.
- swapon –show – lists active swap devices and files
-
Enable swap automatically at boot
Edit /etc/fstab
vi /etc/fstab
Add the following line to the file:
/docker_swap swap swap defaults 0 0
Ensures Linux activates the swap file automatically during boot
Test the configuration:
Confirms that the swap file can be activated using the /etc/fstab configuration.
Recommendation: Read Next: How to delete swap space in Linux after proceeding with the steps above.