Posts

Creating a SWAP space in an AWS Instance



This blog post is about how to create a SWAP file in an AWS Instance. If you are not familiar with SWAP, our blog post about SWAP might help you grasp the concept.



How to create a SWAP space

In the testing environment below, you can see that there is only a memory that the instance is currently using.

[root@test-aws-harukainoue var]# free -m
              total        used        free      shared  buff/cache   available
Mem:            983         226          75           0         681         596
Swap:             0           0           0

Let's add a SWAP file to it.

Prepare a directory called 'swapfile' under /var and create a file called 'swap'.

[root@test-aws-harukainoue var]# mkdir swapfile
[root@test-aws-harukainoue var]# ls -altr
drwxr-xr-x  2 root root    6 Feb  2 04:52 swapfile
[root@test-aws-harukainoue var]# cd swapfile
[root@test-aws-harukainoue swapfile]# pwd
/var/swapfile
[root@test-aws-harukainoue swapfile]# dd if=/dev/zero of=/var/swapfile/swap bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 13.6114 s, 78.9 MB/s
[root@test-aws-harukainoue swapfile]# ls -altr
-rw-r--r--  1 root root 1073741824 Feb 11 08:40 swap
[root@test-aws-harukainoue swapfile]# chmod 600 swap
[root@test-aws-harukainoue swapfile]# ls -altr
-rw-------  1 root root 1073741824 Feb 11 08:40 swap

Note: To avoid accidentally editing the SWAP file, set the permissions to 600 like above.


Then format the swap file for the SWAP space and activate the swap file.

[root@test-aws-harukainoue swapfile]# mkswap ./swap
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=8227fefa-a6da-4c63-a9c3-ae21c06dad30
[root@test-aws-harukainoue swapfile]# swapon ./swap
[root@test-aws-harukainoue swapfile]# free -m
              total        used        free      shared  buff/cache   available
Mem:            983         227          73           0         682         594
Swap:          1023           0        1023
[root@test-aws-harukainoue swapfile]# swapon -s
Filename                                Type            Size    Used    Priority
/var/swapfile/swap                      file            1048572 0       -2

After creating the SWAP space, you need to mount it so that the SWAP space will stay in the instance after rebooting.

[root@test-aws-harukainoue swapfile]# vi /etc/fstab

In the fstab file, add the below and save the file

/var/swapfile/swap swap swap defaults 0 0
:wq

Now, you can see the SWAP space exists after rebooting your instance.

[root@test-aws-harukainoue ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            983         218          78           0         686         604
Swap:          1023           0        1023




This blog post is translated from a blog post written on our Japanese website.

13 views