Skip to content

Vagrant image with docker using packer

I wanted to test a docker setup and the easiest was to do it in a vm. I was looking for a solution as easy as docker, and went with Vagrant. To have a vagrant-managed vm it’s possible to use an existing box, but I’m more comfortable knowing exactly what’s in the boxes I use, so I decided to build one with Packer. This post is based on this blog post and the config and scripts used are public.

The packer config is based on the box ubuntu/jammy64 published by Ubuntu. It is configured to run with VirtualBox, which is thus a requirement to run the image in a vm:

variable "version" {
  type    = string
  default = ""
}

locals { timestamp = regex_replace(timestamp(), "[- TZ:]", "") }

source "vagrant" "myjammy" {
  add_force    = true
  communicator = "ssh"
  provider     = "virtualbox"
  source_path  = "ubuntu/jammy64"
}

build {
  sources = ["source.vagrant.myjammy"]

  provisioner "shell" {
    execute_command = "echo 'vagrant' | {{.Vars}} sudo -S -E bash '{{.Path}}'"
    script = "scripts/install_docker.sh"
  }
}

It uses scripts/install_docker.sh to install docker according Docker’s instructions.

Building the box is done by running packer build docker.pkr.hcl. With the config file used, the output directory is called output-myjammy, under which you find the file package.box which you need to import to make it available to Vagrant:

vagrant box add docker output-myjammy/package.box

I imported the box and named it docker.

To use it, create your project directory and get inside it. Then run

vagrant init docker

which will create a Vagrantfile. This is where you can optionally modify the configuration of your vm. With the Vagrantfile available, you can run start your vm with vagrant up and access it with vagrant ssh. Once in the vm it is possible to run docker as the vargrant user, eg docker ps. When you have finished, exit the vm and either vagrant suspend or vagrant destroy the virtual machine.