Over a million developers have joined DZone.

How to Change the Size of Your Swap File

DZone 's Guide to

How to Change the Size of Your Swap File

Whether your box has run out of space or you have a server with a lot of processes running on it, managing swap space is an essential aspect of system administration.

· DevOps Zone ·
Free Resource

One of the most frequently asked questions in support revolves around how to change the size of the swap file. I'll tackle this topic by providing a short introduction to the matter, with a couple of use cases and a step-by-step guide. Let's get started!

What Is It?

Swap (Virtual Memory) is space on a disk that Linux can use it when it runs out of RAM. Inactive processes can be moved to swap from RAM to make space for active processes.

However, there is a disadvantage since hard disk is much slower than RAM, your server performance can slow down.

Cloud 66 has created a swap file on provisioning servers in root folder /c66-swapfile. The size of the file depends on the free space of the server that is between 3 GB to 256 GB.

Reasons to Change the Size of the Swap File

You may need to change swap in different cases. For example:

  • When your box runs out of spaces, decreasing swap file size is the quickest way that you can release some spaces, especially when you have a huge swap file.
  • When you have a server with lots of processes running on it, increasing swap file size will let the kernel to move inactive processes into swap to make room for active processes in the working memory.

Step-by-Step Guide

The instructions below will help you change your server swap file size to the desired value.

First, you need to create a script that you can re-use.

Create a file named /tmp/swap-file-setter.sh with the script below:

# don't do anything if we already have swap file settings 
if [[ $(swapon -s | wc -l) = 1 ]] ; then 
  echo "Creating your swap file" 
  dd if=/dev/zero of=/c66-swapfile bs=1024 count=$1k 
  mkswap /c66-swapfile swapon /c66-swapfile 
  echo "/c66-swapfile none swap sw 0 0 " >> /etc/fstab 
  chown root:root /c66-swapfile 
  chmod 0600 /c66-swapfile 
  echo "Swap file successfully created" 

Give executing permission to the script:

sudo chmod +x /tmp/swap-file-setter.sh 

Now, you can use the script each time you wish to change the swap file size.

Remove the current swap file.

$ sudo swapoff -a $ sudo rm -f /c66-swapfile 

Create a new swap file using the script above.

sudo /tmp/swap-file-setter.sh <size_in_mb> 

To sum up, managing swap space is an essential aspect of system administration. Always monitor your memory to ensure that you are getting the best result with your current swap file size.

devops ,tutorial ,swap file ,file size

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}