Adding swap

From Newroco Tech Docs
Jump to navigationJump to search

Sometimes it is useful to add additional swap space to a running Linux (or Unix) computer, server or PC.

First create a swap file:

# dd if=/dev/zero of=/addswap1 bs=1024 count=1048576

This creates a file of 1GB with 1048576 blocks of size of 1024 (noting 1024^2=1048576, so a "true" GB is created), where the count can be adapted to create a smaller or larger file as needed - note throughout the name and location of the file can be whatever you choose, but it is best having the word "swap" somewhere in it so that it's clear what it is in the future.

Make the new file into a swap file:

# mkswap /addswap1

Secure the file so it's rw just for root:

# chown root:root /addswap1
# chmod 0600 /addswap1

And add it into the system:

# swapon /addswap1

You can review the available swap space by

# swapon -s

(where you should see the original swap partition, if any, with a higher priority than the newly added swap space; the swap file will be lower performance so only used if necessary. If you're adding a new swap partition or creating the swapfile on a dedicated disk you might want to tune the priorities)

Finally, check to see the system can see the additional swap space.

# free

If you want to make the new swap permanent then edit fstab

# vi /etc/fstab

and append this line

/addswap1       none    swap    sw      0       0

or in some Linux variants

/addswap1       swap    swap    defaults      0       0

(copy all but the mountpoint from any existing swap entry if not sure)

If you just needed the swap space temporarily, say if running a rsync job to move a massive file tree, and would prefer to have the disk space back when you're done, you can remove the swap by

# swapoff /addswap1
# rm /addswap1