Understanding How Docker Swarm Works
Docker Swarm Volumes
Since containers are ephemeral, the data stored inside them can be lost when the container is removed. The same principle applies to services in Docker Swarm, as they're composed of containers.
When running stateful applications such as databases, it's important to persist the data. This is where Docker volumes come into play.
Let's remove the previous service we created:
docker service rm $(docker service ls -q)
To create a volume, we need to run the following command on the manager node:
docker volume create mysql_data
To use the volume in a service, we need to run the following command:
docker service create --name mysql \
--secret mysql_root_password \
-e MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql_root_password \
-e MYSQL_DATABASE=wordpress \
-e MYSQL_USER=wordpress \
--mount type=volume,source=mysql_data,target=/var/lib/mysql \
-d mysql:9.6.0
When you run a service with a volume, the volume is created on the node where the container is running. You can check the volume using the following command:
docker volume ls
Since we have launched a single instance of MySQL, the command above should be executed on the node where the container is running. To determine the location of the container, run the following command:
docker service ps mysql
If the MySQL container is moved to another node, the volume will not be moved along with it. This is because the volume is created on the node where the container is currently running.
To overcome this challenge, we can use constraints to ensure that the container always runs on the same node. To do this, execute the following command:
Remove the previous service and volume:
# remove the old service and the old volumePainless Docker - 2nd Edition
A Comprehensive Guide to Mastering Docker and its EcosystemEnroll now to unlock all content and receive all future updates for free.
Hurry! This limited time offer ends in:
To redeem this offer, copy the coupon code below and apply it at checkout:
