Programmatically Stopping Multiple Docker Services with Labels
In a modern microservices architecture, it is common to have multiple Docker services running simultaneously. Stopping these services programmatically is an essential skill for any DevOps professional. In this article, we will explore how to stop multiple Docker services using labels.
Docker Services and Labels
Docker services are a way to scale and manage containers in a swarm. Labels are metadata tags that you can attach to services, containers, and other Docker objects. Labels allow you to organize and filter objects based on specific criteria. In this example, we will use labels to select and stop multiple Docker services programmatically.
Selecting Services with Labels
To select services based on labels, we can use the docker service ls command with the --filter option. The --filter option allows us to filter services based on specific criteria, such as labels. For example, the following command selects all services with the label role=web:
docker service ls --filter label=role=web
We can use this command to get a list of service IDs that we want to stop. The following command gets a list of service IDs with the label role=web and saves them to a file:
docker service ls --filter label=role=web -q > services.txt
Stopping Services with Labels
Now that we have a list of service IDs, we can stop them using the docker service rm command. The following command stops all services in the file services.txt:
while read service_id; do docker service rm $service_id; done < services.txt
However, stopping services one by one can be slow and inefficient. A better approach is to use the docker service stop command, which stops all instances of a service simultaneously. The following command stops all services with the label role=web:
docker service stop $(docker service ls --filter label=role=web -q)
Stopping Services Programmatically
Now that we know how to stop services with labels, we can use this technique to stop multiple services programmatically. For example, the following script stops all services with the label role=web and waits for 60 seconds before stopping all services with the label role=db:
#!/bin/bash
# Stop web services
docker service stop $(docker service ls --filter label=role=web -q)
sleep 60
# Stop db services
docker service stop $(docker service ls --filter label=role=db -q)
In this article, we have explored how to stop multiple Docker services programmatically using labels. We have covered the following key concepts:
- Docker services and labels
- Selecting services with labels
- Stopping services with labels
- Stopping services programmatically
We have also provided detailed examples using the docker service command and shell scripting. With this knowledge, you can now manage and stop multiple Docker services programmatically, making your DevOps workflow more efficient and automated.