Deploying Docker Swarm with Puppet
In this blog post, I'll show in detail how to run Docker Swarm in a production-ready state, all orchestrated with Puppet. Docker Swarm has a few moving parts, so the first thing we should look at is this: Docker Swarm needs a key/value store in the backend to know where all its member nodes are, who the Swarm master is, etc. For the examples in this blog post, we are going to use Consul, but you could very easily swap Consul with etcd or Zookeeper, depending on what you already have in your environment.
The great thing is, there is already an awesome module for Consul on the Puppet Forge, written by Kyle Anderson. We will be using this module to install and configure Consul. The bootstrap node gets set up like this:
And members of the cluster get set up like this:
Now that we have a Swarm backend, we can install Docker Swarm. You can get the Docker Swarm module from the Puppet Forge here: https://forge.puppetlabs.com/scottyc/docker_swarm.
Again, there are two blocks of code we will need: one to set up the master or manager, and another to join members to the cluster. For the initial cluster, we will create a Swarm cluster called
We will then deploy the Swarm managers. It is a best practice to have more than one manager, as the manager provides the vital function of controlling the state of the cluster. If you have more than one manager, the module will set up replication for you. We set up the managers with this code:
The next thing to configure is a private Docker network, in case we need to link our containers:
Now we have our Swarm cluster up and running, we will want to deploy applications to the nodes in the cluster. In this example, we will deploy an ELK stack. We will need to set up service discovery to allow external services from the Swarm cluster to find our containers. To do this, we will install the bind package and point our DNS resolver to Consul:
Here's the code for our two template files:
The last piece of the puzzle for service discovery is an application that will register our containers as they spawn. For this we will use registrator, and we will install it using Docker Compose.
Then we can deploy our ELK stack:
From the code you can see that we are using our service discovery address to connect to Logstash:
One of the cool features released in Swarm v1.1 and above is rescheduling containers on node failure. You can see that in our Kibana container, we are declaring
reschedule:on-node-failure. If the node fails, Kibana will spawn on a healthy node. The Swarm module supports this, as the provider checks the cluster for the container, not the individual node. Thus, the module gives you the resiliency Swarm offers, while keeping the advantage of Puppet's idempotency.
For people who would like to play with the code in this blog post, I have created a fully functional demo lab that can be found on my GitHub page.
Scott Coulton is a solution architect at HealthDirect Australia.