Setting up a Docker Swarm cluster with Vagrant and Ansible

For a Docker Swarm cluster I will use in this example: 1 manager node and 2 worker nodes. They will be launched by Vagrant with VirtualBox using the Ubuntu 16.04 image.

First we define the nodes in the Vagrantfile:

Make sure the nodes can reach each other in the same network.

Then we need to provision those nodes with Docker. For this I chose Ansible.

Let’s first create an Ansible play that installs Docker:

Then we need to initialize the Swarm cluster on the manager. For this I defined a separate Ansible play:

The last task in provisioning the master node is to store the “join token” in a shared file so that the workers can join the newly created cluster.

To have the workers join the swarm, create a separate Ansible play for the workers:

Finally add the Ansible provisioning to the Vagrantfile:

Note: because Ubuntu 16.04 ships with Python 3 instead of 2.x, we need to explicitly set the ansible_python_interpreter variable.

After this, just run:

And it will launch and provision the Docker Swarm cluster for you. When the cluster is running you can connect to the manager node at 10.0.3.2 and start deploying services!

Tom Wetjens

Tom is an agile full stack developer with a lot of experience in back end and front end development with Java, Spring, Angular and React. And continuous delivery pipelines based on Maven, Gradle and Docker.

More Posts - Website

Follow Me:
TwitterLinkedIn