How do I create a swap file in linux?

Creating a swapfile in linux

1). log in as root in your linux computer.

2). Determine if you already have a swapfile. type this command free -h

You will see something like this below. You will observe that Swap has 0B meaning no swap file
total       used       free     shared    buffers     cached
Mem: 3.9G 3.5G 406M 106M 116M 1.1G
-/+ buffers/cache: 2.3G 1.6G
Swap: 0B 0B 0B


How to add Swap File

Follow these steps to add 4GB of swap to your server. If you want to add 2GB instead of 1 GB, replace 4G with 2G.

  1. Create a file that will be used for swap:

    sudo fallocate -l 4G /swapfile

    If faillocate is not installed or if you get an error message saying fallocate failed: Operation not supported then you can use the following command to create the swap file:
    sudo dd if=/dev/zero of=/swapfile bs=1K count=4M
    So by using multiplicative suffixes it's easier to count (1K * 4M = 4 GiB).

    Only the root user should be able to write and read the swap file. To set the correct permissions type:
  2. sudo chmod 600 /swapfile

    Use the mkswap utility to set up the file as Linux swap area:
  3. sudo mkswap /swapfile

    Enable the swap with the following command:
  4. sudo swapon /swapfile

    To make the change permanent open the /etc/fstab file and append the following line:
    /etc/fstab
    /swapfile swap swap defaults 0 0

    To verify that the swap is active, use either the swapon or the free command as shown below:
  5. sudo swapon --show
    If the above command does not work type the first command given in this guide which is free -h

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How do I change my remember password options in Google Chrome

Manage your website passwords This article applies to the Google Chrome browser on Windows,...

Change time is Gmail

Correct Your Gmail Time Zone To set your Gmail time zone: Click the gear in your Gmail's...

How to speed up Windows XP use at your own risk

Warning: occasionally people break their PC badly by using this list of suggestions. Usually...

How to run cmd in escalated mode with admin rights to modify firewall

a solution: runas /user:administrator@domainname.local cmd then in the resulting command...

How do I enable auto login in Windows

This article describes how to configure Windows to automate the logon...