Skip to content
Home » Linux » How to Enable a Swap File on Linux

How to Enable a Swap File on Linux

There's only 512MB physical memory and no swap on the server:

[root@test ~]# free
             total       used       free     shared    buffers     cached
Mem:        498388     340172     158216          0      14428     126892
-/+ buffers/cache:     198852     299536
Swap:            0          0          0

And we'd like to take advantage of the virtual memory - swap in case the server runs into out of memory. Let's see what swap is used currently:

[root@test ~]# swapon -s
Filename                                Type            Size    Used    Priority

Nope, there's no swap enabled.

Now, let's begin to create and enable a swap file. Alternatively, you may consider to increase swap partition for your server.

  1. Initialize 512MB swap file by dd:
  2. [root@test ~]# dd if=/dev/zero of=/swapfile bs=1024 count=512k
    524288+0 records in
    524288+0 records out
    536870912 bytes (537 MB) copied, 54.5613 s, 9.8 MB/s
  3. Make the swap:
  4. [root@test ~]# mkswap /swapfile
    mkswap: /swapfile: warning: don't erase bootbits sectors
            on whole disk. Use -f to force.
    Setting up swapspace version 1, size = 524284 KiB
    no label, UUID=ccb357c3-b325-468d-8db2-6a4e3bdfde93
  5. Enable the swap file:
  6. [root@test ~]# swapon /swapfile
    [root@test ~]# swapon -s
    Filename                                Type            Size    Used    Priority
    /swapfile                               file            524280  0       -1
  7. Persist the setting to /etc/fstab:
  8. [root@test ~]# vi /etc/fstab
    ...
    /swapfile               swap                    swap    defaults        0 0
    ...

  9. Change the default permission into private:
  10. [root@test ~]# ls -l /swapfile
    -rw-r--r--. 1 root root 536870912 Apr 15 11:55 /swapfile
    [root@test ~]# chmod 600 /swapfile
    [root@test ~]# ls -l /swapfile
    -rw-------. 1 root root 536870912 Apr 15 11:55 /swapfile

Now, we have swap enabled on the server:

[root@test ~]# free
             total       used       free     shared    buffers     cached
Mem:        498388     489452       8936          0      12368     260872
-/+ buffers/cache:     216212     282176
Swap:       524280          0     524280

We made it.

Leave a Reply

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