I'll walk you through setting up Docker Swarm with Portainer for container orchestration and management.
Prerequisites
Before starting, ensure you have Docker installed on all nodes that will participate in your swarm. You'll need at least one manager node, though for production environments, having 3 or 5 managers provides better fault tolerance.
Initialize Docker Swarm
On your designated manager node, initialize the swarm by running:
bash
docker swarm init --advertise-addr <MANAGER-IP>
Replace <MANAGER-IP> with your manager node's IP address. This command will output a join token that looks something like:
Save this token as you'll need it to add worker nodes to your swarm.
Add Worker Nodes
On each worker node, run the join command that was generated in the previous step. If you need to retrieve the join token again, you can run this on the manager:
bash
docker swarm join-token worker
For additional manager nodes, get the manager join token:
bash
docker swarm join-token manager
Deploy Portainer
Now let's deploy Portainer as a service in your swarm. First, create a network for Portainer:
Once deployed, you can access Portainer through your browser at http://<MANAGER-IP>:9000. On first access, you'll need to create an admin user. Set a strong password as this will be your main administrative account.
After logging in, Portainer will automatically detect your Docker Swarm environment. You'll see all your nodes, services, and stacks in the web interface.
Verify Your Setup
To confirm everything is working correctly, check your services:
bash
docker service ls
You should see both portainer and portainer_agent services running. You can also verify node status:
bash
docker node ls
This will show all nodes in your swarm and their current status.
Security Considerations
For production environments, consider these security enhancements: enable TLS/SSL for Portainer by adding certificates, restrict access to the Portainer interface using firewall rules or reverse proxy authentication, use secrets management for sensitive data instead of environment variables, and regularly update both Docker and Portainer to the latest versions.
Troubleshooting Tips
If nodes can't join the swarm, verify that ports 2377 (cluster management), 7946 (TCP/UDP for node communication), and 4789 (UDP for overlay network) are open between all nodes. Also ensure system clocks are synchronized across all nodes using NTP.
If Portainer can't connect to the agent, check that the portainer_agent_network overlay network exists on all nodes and that the agent service is running globally.
With this setup complete, you now have a fully functional Docker Swarm cluster managed through Portainer's intuitive web interface, allowing you to deploy and manage containerized applications across multiple nodes efficiently.