How to save and reuse a vagrant machine as vagrant box?

Are you using Vagrant for your application development locally?  Do you often encounter situations in which you are forced to destroy vagrant machine and create it again? Then this blog is for you.

It is often the situation that you will be using an operating system as base box from Vagrant Atlas and will be installing softwares, packages etc. on top of it. The base box will be specified in your Vagrantfile as value of property config.vm.box.  This base box and everything on top of it makes the vagrant machine. When you destroy a vagrant machine, all the stuffs installed on top of base box will be lost. It is possible to save the vagrant machine as a box and reuse it without having to install all the required package when you want to start over again.

Now lets see how to create a vagrant box from the vagrant machine. At first, stop your applications, if they are running inside your vagrant machine.

Here I assume that you are using Ubuntu as base box. If you use Docker like me, then you have to remove all Docker containers (PS: The following command will remove all Docker containers along with volumes. Make a backup of data in database based Docker containers if needed).

sudo docker rm -v $(sudo docker ps -aq)

Remove all dangling volumes using the following command

sudo docker volume rm $(docker volume ls -qf dangling=true)

Clear APT cache to prevent storing unnecessary data

sudo apt-get clean

Clear executed commands history and exit from the vagrant machine

cat /dev/null > ~/.bash_history && history -c && exit

Then, suspend the vagrant machine

vagrant suspend

Now we can create a new vagrant box from the vagrant machine using the following command

vagrant package --output my-app-vagrant.box

You can then destroy the vagrant machine

vagrant destroy

To use the newly created vagrant box, execute the following command

vagrant box add myAppBox my-app-vagrant.box

Then go to the Vagrant file. Comment out the line containing ‘config.vm.box’ property and add the following line below it

config.vm.box = "myAppBox"

After this when you start the vagrant machine using vagrant up command, you will be using the newly created box.

You will realize that this time it took only less time to start the vagrant machine 🙂 . The box needs to be created only once and then you can use it to start a fresh vagrant machine fastly over and over again.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: