Virtual Development Server: Add swapfile to VirtualBox as requirement for installing Oracle or build Oracle docker images

Posted by Torsten Kleiber on August 19, 2016 Tags: Virtual-Development-Server Continous-Integration Infrastructure-as-Code Linux Oracle Vagrant VirtualBox Docker

As I want later build Oracle docker images, some of this need a swapfile. Per default my used Vagrantbox does not have one, so later steps will fail.

As in the last blog I use a Vagrant shell provider.

...
# add swapfile to the box
config.vm.provision :shell, :path => "add_swap.sh"
...

This calls the script add_swap.sh in the created VirtualBox machine. Make sure, that you create your swapfile on a supported file system.

#!/bin/sh

# size of swapfile in megabytes
swapsize=2100

# does the swap file already exist?
grep -q "swapfile" /etc/fstab

# if not then create it
if [ $? -ne 0 ]; then
  echo 'swapfile not found. Adding swapfile.'
  # allocate the disk space
  sudo fallocate -l ${swapsize}M /home/swapfile
  # only owner can read and write
  sudo chmod 600 /home/swapfile
  # sets up swap area in the file
  sudo mkswap /home/swapfile
  # enable file for paging and swapping
  # if this comes with "swapon failed: Invalid argument",
  # check if the filesystem is supported for swap, xfs eg. is not
  sudo swapon /home/swapfile
  # mount the swapfile at boot
  echo '/home/swapfile none swap defaults 0 0' >> /etc/fstab
else
  echo 'swapfile found. No changes made.'
fi

# output results to terminal
df -h /home/swapfile
cat /proc/swaps
cat /proc/meminfo | grep Swap

Now you have to recreate the VirtualBox machine via

vagrant destroy
vagrant up

In the output you can now see, how the swapfile is added.

...
==> default: Running provisioner: shell...
default: Running: C:/Users/torst/AppData/Local/Temp/vagrant-shell20160819-14324-1a10xs8.sh
==> default: swapfile not found. Adding swapfile.
==> default: Setting up swapspace version 1, size = 2150396 KiB
==> default: no label, UUID=20ff8dbf-6282-4ba6-abe4-05c04c74aac8
==> default: Filesystem              Size  Used Avail Use% Mounted on
==> default: /dev/mapper/linux-home  3.8G  2.4G  1.5G  63% /home
==> default: Filename                           Type            Size    Used    Priority
==> default: /home/swapfile                          file               2150396 0       -1
==> default: SwapCached:            0 kB
==> default: SwapTotal:       2150396 kB
==> default: SwapFree:        2150396 kB
...

Here you find the source code for this blog.

Here you find more about the topic "Virtual Development Server".

That’s it!

References: