How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file

How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file

How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file?

When physical RAM is already in use, Amazon EC2 instances use swap space as a short-term replacement for physical RAM.

Contents of RAM that aren’t in active use or that aren’t needed as urgently as other data or instructions can be temporarily paged to a swap file. This frees up RAM for more immediate use.

The problem is when you don’t have swap space.

How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file

Use the dd command to create a swap file on the root file system

Command 1
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

output
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 31.5064 s, 68.2 MB/s

Command 2
sudo fallocate –length 2G /swapfile

If the above command is throwing any error (new version of Ubuntu throw error on command –length)
try this sudo fallocate –l 2G /swapfile

Command 3
sudo chmod 600 /swapfile

Command 4
sudo mkswap /swapfile

output
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=e508f3b2-8eaa-4b5a-8bbe-98d150b7da96

Command 5
sudo swapon /swapfile

Enable the swap file at boot time by editing the /etc/fstab file. so that it wont change after restarting the server.

Open the file in the editor:

Command 6
sudo vi /etc/fstab
Add the following newline at the end of the file, save the file, and then exit:

Command 7
/swapfile swap swap defaults 0 0

# To add swap space in centos 6
Basically, we are going to create 1GB file that will consist of zeros only and use that as a swap later.

# dd if=/dev/zero of=/swapfile bs=1M count=1024
Next, we need to set up file so it is can be used as swap space. We will use mkswap command for that:

# mkswap /swapfile
The swap file must be owned by root and have proper permissions:

#chown root:root /swapfile
#chmod 0600 /swapfile
Once this is done, the only thing left is to activate and start using the swap space.

# swapon /swapfile

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.