1. The principle #
Several machines, a single file.
Why automate joining #
Docker Swarm needs one node to initialize the cluster (docker swarm init) and the others to join it with a token. Done by hand, it is tedious and error-prone. With Vagrant, the manager writes its token into the shared /vagrant folder, which the workers read when they start.
Creation order: Machines are created in the order of the Vagrantfile: the manager must be declared first so that the token exists when the workers start.
2. The Vagrantfile #
A loop and two scripts.
Vagrantfile #
NODES = { "manager1" => "192.168.56.10", "worker1" => "192.168.56.11", "worker2" => "192.168.56.12" }
Vagrant.configure("2") do |config|
config.vm.box = "bento/ubuntu-24.04"
config.vm.provision "shell", path: "scripts/docker.sh" # commun : installer Docker
NODES.each do |name, ip|
config.vm.define name do |node|
node.vm.hostname = name
node.vm.network "private_network", ip: ip
node.vm.provider "virtualbox" do |vb|
vb.memory = 1536
vb.cpus = 2
end
role = name.start_with?("manager") ? "manager" : "worker"
node.vm.provision "shell", path: "scripts/#{role}.sh", args: [ip, NODES["manager1"]]
end
end
endscripts/docker.sh #
#!/usr/bin/env bash
set -euo pipefail
curl -fsSL https://get.docker.com | sh
usermod -aG docker vagrantscripts/manager.sh and scripts/worker.sh #
# manager.sh
set -euo pipefail
docker swarm init --advertise-addr "$1"
docker swarm join-token -q worker > /vagrant/worker.token
# worker.sh
set -euo pipefail
docker swarm join --token "$(cat /vagrant/worker.token)" "$2:2377"3. Starting and using the cluster #
Check, deploy, scale.
Commands #
vagrant up # crée les trois nœuds dans l'ordre
vagrant ssh manager1 -c "docker node ls" # trois nœuds Ready, un Leader
vagrant ssh manager1 -c "docker service create --name web --replicas 3 -p 8080:80 nginx"
vagrant ssh manager1 -c "docker service ps web"
vagrant ssh manager1 -c "docker service scale web=6"
curl http://192.168.56.11:8080 # le maillage de routage répond sur chaque nœud
vagrant destroy -f && rm -f worker.tokenPitfalls #
- Advertise interface: without
--advertise-addr, Swarm picks VirtualBox's NAT interface (10.0.2.15), identical on every machine, and joining fails. - Stale token: delete
worker.tokenafter avagrant destroy. - Ports: 2377 (management), 7946 (communication) and 4789/udp (overlay network) must be open between the nodes.
Good practice: For a more resilient cluster, declare three managers: Swarm then tolerates the loss of one manager (Raft quorum).
