Adding Swap memory at system startup

How to increase swap memory? And how to add this memory at startup?
If we need to increase memory swap, we can do it with a swap formatted file.
Some Cloud providers do not set swap memory in their VPS, so it is up to the system administrator to manage and provide a solution if needed. This way is specially useful in this cases.
It can also be useful for low swap memory systems, you can use this method to increase swap memory either temporally or not.
We will see also how to add this swap memory file at system startup.
We will work connected as root, or use sudo in each of the commands.

Creating and formatting the swap file

Creating the file

The first step is deciding the size this file is going to have, therefore the amount of swap memory we are increasing.
Let’s say we want to increase 1024 MB, so we need to obtain the block size, we do it this way:

1024 * 1024 = 1048576

If we would want 512 MB:

1024 * 512 = 524288

Finally we create the file. In this example with a 1024 MB file size. The file is created in “/” and named swapfile1.

dd if=/dev/zero of=/swapfile1 bs=1024 count=1048576

As usual, be careful with “dd” command.

Formatting the swap file

Now we have to set permissions and format the file.

PERMISSIONS

chown root:root /swapfile1
chmod 0600 /swapfile1

Format

mkswap /swapfile1

Increase swap

Finally, when we have our swapfile ready, it’s time to add it to the system, and it will be in use immediately.

swapon /swapfile1

Decrease Swap

If we want to reduce the swap by deactivating the swapfile, we do this:

swapoff /swapfile1

If the swapfile was not in use, it will be immediate, otherwise it can take a long time to release the swapfile.

Small sample script

We can create a small script with the commands we see previously, it can be executed at demand or at the startup.

#!/bin/bash
/bin/dd if=/dev/zero of=/swapfile1 bs=1024 count=1048576
/bin/chown root:root /swapfile1
/bin/chmod 0600 /swapfile1
/sbin/mkswap /swapfile1
/sbin/swapon /swapfile1

In this example we store this script in “/bin” and we name it “addswapfile.sh”.
Make sure that your script is executable:

chmod u+x /bin/addswapfile.sh

Increase at startup

A simple way of executing this script is by using “cron”. So with “crontab -e” edit your crontab and add the following:

@reboot /bin/addswapfile.sh

 

Leave a Reply

Your email address will not be published. Required fields are marked *