Adding Swap File to a Linux System



Traditionally we add a swap partition in our systems during or after a fresh installation process. This approach often results in a disk with scattered partitions hard to administer, among further practical issues.

In this post I would discuss how to utilise a chunk of file as a swap partition.

Let's check our system


$ free --human # Revolutionary indeed d('_')b


total used free shared buff/cache available

Mem: 5.7Gi 862Mi 4.0Gi 143Mi 869Mi 4.5Gi

Swap: 0B 0B 0B


NOTE

OK, we've no swap in the system yet. Before making a swap file chunk, let's have a look at the scenario under-the-hood whether we will pick `dd` of `fallocate` tool.

Among them, `fallocate` is faster indded but we'll use `dd` for avoiding any further issue.

The `swapon` manpage says "... fallocate(1) may be interpreted as files with holes too depending of the filesystem. ...It is recommended to use dd(1) and /dev/zero to avoid holes on XFS and ext4."

Let's make our hands dirty


1. Create an XGB file

Create a `swapfile` in the `/` directory.

$ sudo dd if=/dev/zero /of=/swapfile bs=1G count=X

Explanation: Make a file of X GiB where each block will be `bs=1GB` in size (X * 1GB). We can define Mega, Giga etc. sizes in `bs=`.


2. Make swap

Flag the file chunk as a swap partition.

$ sudo mkswap /swapfile


3. Change mode

Only the root user can read(4) and write(2) on this file

$ sudo chmod 600 /swapfile


4. Swap on the file

$ sudo swapon /swapfile


5. Add to file system tab

Let's add this line to the /etc/fstab file

/swapfile none swap sw 0 0


Now check whether everything is ok.

# swapon -s

Filename Type Size Used Priority

/swapfile file 3145724 0 -2



Conclusion:

We can automate the process with a bash script which is available here. You can watch the video tutorial here

Comments