Docker – Swarm commands

By | 20/04/2022

In this post, we will see some Swarm commands that could help us in our docker projects.
But first of all, what is Docker Swarm?
Docker Swarm is an orchestration management tool that runs on Docker applications and it helps us in creating and deploying a cluster of Docker nodes.
Swarm is directly integrated into the Docker CLI and it means we don’t need to add any additional orchestration software or other tools to create or manage a swarm.
We can say that Swarm is similar at Kubernetes with less features but is a perfectly fine solution for smaller workloads.
For all information: https://docs.docker.com/engine/swarm/

FOR THIS POST I HAVE USED A WINDOWS MACHINE BUT, THE COMMANDS, ARE THE SAME FOR LINUX AND MAC TOO.


CREATION OF A SWARM CLUSTER

docker swarm init


LIST OF NODES

docker node ls


RETRIEVE THE JOIN COMMAND FOR A WORKER NODE

docker swarm join-token manager


DEPLOY A SERVICE TO THE SWARM
A service is the definition of the tasks to execute in the nodes.
When we create a service, we have to specify which container image to use and the commands to execute inside running containers.
For example, if we want to create a service to run a MongoDB container specifying the root user, we can run the command:

docker service create --name dockermongo -e MONGO_INITDB_ROOT_USERNAME=admindb -e MONGO_INITDB_ROOT_PASSWORD=pass123 mongo


LIST OF SERVICES

docker service ls


GET SERVICE’S DETAILS

docker service inspect 'name of instance'


SCALE A SERVICE

docker service scale 'name of instance'='number of instance'


LIST OF ALL INSTANCES OF A SERVICE

docker service ps 'name of instance'


REMOVE A SERVICE

docker service rm 'name of instance'


CREATING A STACK
With Docker Swarm, we can use docker stack deploy to deploy a complete application stack to the swarm. The deploy command accepts a stack description in the form of a Compose file.

First of all, we define a docker-compose file called docker-compose.yml:

version: '3'
services:
  dockermongo:
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admindb 
      - MONGO_INITDB_ROOT_PASSWORD=pass123 
    volumes:
      - dbmongo:/data/db
    ports:
      - 27017:27017
  dockermongoexpress:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=admindb
      - ME_CONFIG_MONGODB_ADMINPASSWORD=pass123
      - ME_CONFIG_MONGODB_SERVER=dockermongo
volumes:
  dbmongo:
    driver: local



Then, in order to create a Stack, we run the command:

docker stack deploy 'name stack '-c 'name file docker compose'


LIST OF STACKS

docker stack ls


STACK INFO

docker stack ps 'name stack'


LEAVE THE SWARM CLUSTER

docker swarm leave --force



Leave a Reply

Your email address will not be published.