Linux: Create and Mount Swap via SSH

Some server that I am working with has no swap space mounted in the server. Swap is necessary as backup of our physical memory in case system needs more memory than what it has at that time and also increase application loading speed especially when starting and closing application.

Swap space can be setup in 2 ways, as partition or as a file. Since this server is already online and I have many free partition left in “/” partition, so it may good for me just to create swap file rather than swap partition.

My variables as below:

OS: RHEL 5.7 64bit (Tikanga)
Swap file location: /mnt/swapfile
Swap size: 4 GB

1. Current swap status:

$ free -m
             total       used       free     shared    buffers     cached
Mem:          1001        984         17          0          4        890
-/+ buffers/cache:         89        912
Swap:            0          0          0

2. Make sure the swap is turn off before we start any changes to:

$ swapoff -a

3. We need to create empty file using dd command. I am using this bit calculator to help me calculate how much 4 GB in kilobytes. Using block size 1024 (1 kilobyte = 1024 bytes) , we need 4194304 kilobytes which equal to 4 GB.

$ dd if=/dev/zero of=/mnt/swapfile bs=1024 count=4194304
4194304+0 records in
4194304+0 records out
4294967296 bytes (4.3 GB) copied, 22.7549 seconds, 189 MB/s

4. Lets create the swap space for the swap file:

$ mkswap /mnt/swapfile
Setting up swapspace version 1, size = 4294963 kB

5. Swap space created. Now we need to mount it into the system via /etc/fstab. Open the file via text editor:

$ vi /etc/fstab

And add following line:

/mnt/swapfile           swap                    swap    defaults        0 0

6. Now lets activate the swap space into system:

$ swapon -a

7. Lets check the active swap space now:

$ free -m
             total       used       free     shared    buffers     cached
Mem:          1001        984         17          0          4        890
-/+ buffers/cache:         89        912
Swap:         4095          0       4095

Done. You can repeat similar steps to manage your swap file. Maybe some day when you realized you dont need to have big-size swap, then you can turn swap off, delete swap file, recreate the swap file with smaller size and turn swap on. That’s all!

Leave a comment

Leave a Reply

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