Prune services no longer referenced in the compose file
In this step, we will modify our docker-compose.yml
file again, this time removing a service. When we redeploy the stack, Docker Swarm will detect that a service is no longer defined in the Compose file and will remove it. This process is sometimes referred to as "pruning" services.
First, let's edit the docker-compose.yml
file to remove the alpine
service.
nano ~/project/docker-compose.yml
Remove the entire alpine:
section from the file. The file should revert back to its original state, defining only the web
service:
version: "3.8"
services:
web:
image: nginx:1.21.6
ports:
- "80:80"
Save the modified file by pressing Ctrl + X
, then Y
, and then Enter
.
Now, deploy the stack again using the modified docker-compose.yml
file.
docker stack deploy -c ~/project/docker-compose.yml mywebstack
Docker Swarm will compare the current state of the mywebstack
stack with the definition in the updated docker-compose.yml
file. It will notice that the alpine
service is no longer present in the file and will remove the corresponding service and its tasks from the Swarm. You should see output indicating that the alpine
service is being removed.
To verify that the alpine
service has been removed, list the services in the stack again.
docker stack services mywebstack
You should now only see the mywebstack_web
service listed. The mywebstack_alpine
service should be gone.
Finally, to clean up the Swarm environment, we can remove the entire stack.
docker stack rm mywebstack
This command removes the mywebstack
stack, including all its services and tasks. You should see output confirming the removal.
To verify that the stack is removed, list the stacks again.
docker stack ls
The mywebstack
should no longer be listed.
You have successfully pruned a service from your stack by removing it from the docker-compose.yml
file and redeploying, and then cleaned up the environment by removing the entire stack.