The "docker container run" command has two options that allow you to set labels for your containers:
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
Let's try the option "
-l" ("
--label"):
$ docker container run --rm -d --label my_label_1="my label 1 value" --label my_label_2="my label 2 value" nginx:latest
9da697d8336291e8afb968224ff9402bf2d1dfc904275c7c392e44d8c1155e6b
Let's check the labels:
$ docker container inspect b0411f9636 --format '{{json .Config.Labels }}' | jq
{
"my_label_1": "my label 1 value",
"my_label_2": "my label 2 value"
}
The two labels were set properly. We can use them to filter containers:
$ docker container ls -a --filter label="my_label_1=my label 1 value"
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b0411f9636d8 nginx:latest "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 80/tcp modest_ishizaka
In some cases, setting labels using the option "
--label" can be cumbersome especially if we want to set many of them.
Optionally, you can group all the labels in a property file and use the option "
--label-file" to pass the file to "
docker container run" command.
Let's create a property file:
$ vi label-file-1
my_label_1=my label 1 value
my_label_2=my label 2 value
my_label_3=my label 3 value
Let's use the option "--env-file":
$ docker container run --rm -d --label-file label-file-1 nginx:latest
cc5164ddc8993f3d383e00345195dc495d72479271752bf812f11024208cc109
Let's check the labels:
$ docker container inspect cc5164ddc --format '{{json .Config.Labels }}' | jq
{
"my_label_1": "my label 1 value",
"my_label_2": "my label 2 value",
"my_label_3": "my label 3 value"
}