Docker Swarm Basic Commands

Adler @ 2018-06-27

Basic commands

docker swarm init
docker node ls

docker service create --name alpine alpine ping
docker service ls
docker service ps alpine
docker service logs alpine
docker service update alpine --replicas 2
docker container rm -f 759896ca6eb7 # if a replica is destroyed, swarm will rebuild it

Build a swarm cluster on Ubuntu


curl -fsSL -o


docker swarm init --advertise-addr
docker swarm join-token manager

Join other nodes into the same cluster using the join token.

Promote a node to manager:

docker node update --role manager node2
docker node ls

Run a service:

docker service create --replicas 3 alpine ping

cluster networking

docker network create --driver overlay drupal
docker service create --name postgres --network drupal -e POSTGRES_PASSWORD=12345678 postgres
docker service create --name drupal --network drupal -p 80:80 drupal

go to the IP address and install drupal, it should know the db from the service name "postgres"


A secret can be crated with specifying a text file.

docker secret create foo bar.txt

and pass the secret as a flag when creating a service:

docker service create --name psql --secret psql_user --secret psql_password \
  -e POSTGRES_USER_FILE=/run/secrets/psql_user \
  -e POSTGRES_PASSWORD_FILE=/run/secrets/psql_password \

When passing a --secret flag, it will create a secret file in the service under /run/secrets directory, and that's why we specify the paths if we want to read the secrets.

To remove a secret in a running service:

docker service update --secret-rm psql_user postgres

Secrets in docker-compose.yml

secrets are only available on docker-compose version 3.1 or later. (stack feature starts at version 3)

The structure looks like this:

version: "3.1"

    image: postgres:9.6.8
      - psql_user
      - psql_password
      POSTGRES_PASSWORD_FILE: /run/secrets/psql_password
      POSTGRES_USER_FILE: /run/secrets/psql_user

    file: ./psql_user.txt
      name: psql_password

or other syntax is available.

Use stack deploy and the secrets will be created automatically.