Why use label in docker-compose.yml, can't environment do the job?

Viewed 2476

I am learning docker now. I am trying to figure out what kind of problem Docker label can solve.

I can understand why use label in Dockerfile, e.g add build-related metadata, but I still don't get why using it in docker-compose.yml? What is the difference between using labels vs environment? I assume there will be different use cases but I just can't figure it out.

Can someone give me some practical example?

Thanks

3 Answers

docker-compose.yml is used by docker-compose utility to build and run the services which you have defined in docker-compose.yml
While working with docker-compose we can use two thing

  1. docker-compose build this will build the services which is defined under docker-compose.yml but in order to run this services it has to have a image which is with docker-engine if you do docker image ls you find the images which is built up with the docker-compose and inspect it there you find a label which defines the metadata of that particular image.
  2. docker-compose up this will run the services which is built up in docker-container build now this running container has to have some metadata like env this is set with enviroment in docker-compose.yml

P.S. :- This is my first answer in stack overflow. If you didn't get just give a comment I will try to explain my best.

Another reason to use labels in docker-compose is to flag your containers as part of this docker-compose suite of containers, as opposed to other purposes each docker image might get used for.

Here's an example docker-compose.yml that shares labels across two services:

x-common-labels: &common-labels
  my.project.environment: "my project"
  my.project.maintainer: "me@example.com"

services:
  s1:
    image: somebodyelse/someimage
    labels:
      <<: *common-labels
    # ...
  s2:
    build:
      context: .
    image: my/s2
    labels:
    <<: *common-labels
    # ...

Then you can do things like this to just kill this project's containers.

docker rm -f $(docker container ls --format "{{.ID}}" --filter "label=my.project.environment")

re: labels vs. environment variables

Labels are only available to the docker and docker-compose commands on your host.

Environment variables are also available at run-time inside the docker container.

LABEL can be utilized to embed as much metadata as possible about the Docker image, so to make it easier to work with.

Some main purposes of adding LABEL to a Docker image are:

  • As a documentation.
    You can provide author, description, link to a usage instructions etc.

  • For versioning.
    You can ensure that some new features even with the same latest tag will be applicable for certain versions, so might not broke some old existing features.

  • Any other metadata for programmatic access.

This page provides a guideline and the most common usages of Docker LABEL.

Related