Filter nodes by node label
In this step, we will learn how to filter nodes based on labels assigned to them. Node labels are key-value pairs that you can attach to nodes for organizational purposes or to control service placement.
First, let's add a label to our manager node. We'll add a label location=datacenter1
. To do this, we use the docker node update
command followed by the node ID and the --label-add
flag.
Get the node ID again using docker node ls -q
:
NODE_ID=$(docker node ls -q)
echo $NODE_ID
Now, update the node with the label:
docker node update --label-add location=datacenter1 $NODE_ID
You should see output confirming the node update.
To verify the label has been added, you can inspect the node:
docker node inspect $NODE_ID
Look for the Labels
section in the output. You should see "location": "datacenter1"
.
Now, let's filter the nodes based on this label. We use the --filter
flag with the label
key and the label in the format key=value
.
docker node ls --filter label=location=datacenter1
This command will display only the nodes that have the label location
with the value datacenter1
. In our case, it will show our manager node.
You can also filter for nodes that have a specific label key, regardless of its value, by just providing the key:
docker node ls --filter label=location
This will show all nodes that have the location
label defined.