39

I had problem to get the value from the map list due to the key has "." inside.

docker inspect jenkins
  Config: {
  ..
      "Labels": {
            "com.docker.compose.config-hash": "85bcf1e0bcd708120185a303e2a8d8e65543c1ec77ec0c6762fc057dc10320aa",
            "com.docker.compose.container-number": "1",
            "com.docker.compose.oneoff": "False",
            "com.docker.compose.project": "new",
            "com.docker.compose.service": "sc2",
            "com.docker.compose.version": "1.5.2"
        }
    }
}

I can get map list

docker inspect -f {{.Config.Labels}} new_sc2_1
map[com.docker.compose.config-hash:85bcf1e0bcd708120185a303e2a8d8e65543c1ec77ec0c6762fc057dc10320aa com.docker.compose.container-number:1 com.docker.compose.oneoff:False com.docker.compose.project:new com.docker.compose.service:sc2 com.docker.compose.version:1.5.2]

But how can I get the project name new from key com.docker.compose.project

docker inspect -f {{.Config.Labels.com.docker.compose.project}} new_sc2_1
<no value>
William Desportes
  • 1,412
  • 1
  • 22
  • 31
Larry Cai
  • 55,923
  • 34
  • 110
  • 156

2 Answers2

68

You can use index to get the value of that key (wrapped for readability);

docker inspect \
  --format '{{ index .Config.Labels "com.docker.compose.project"}}' \
  new_sc2_1

That should give you the name of the project

thaJeztah
  • 27,738
  • 9
  • 73
  • 92
  • 3
    FWIW I tried this in PowerShell and had to add the backtick (`) character in front of the inner double quotes to properly escape. \\`"com.docker.compose.project\\`" – devlife Jun 26 '18 at 16:16
  • Changed the example to use single quotes for the outer quotes, that should work as well, and then escaping should not be needed (haven't tried on PowerShell) – thaJeztah Jan 04 '19 at 22:50
  • Trying to use it in docker-compose for logging driver like this: `loki-external-labels: container_name={{.Name}},cluster=${COMPOSE_PROJECT_NAME},service={{ index .Config.Labels 'com.docker.compose.service' }}` What I do wrong if it fails with _loki: could not expand label value_ ? – wapmorgan Aug 20 '19 at 13:41
13

You could pipe the output of docker inspect to jq. Given content like this:

...
        "Labels": {
            "com.docker.compose.config-hash": "a804d541a5828f4aaf17df862b650e58ac5bae77b70ff5ebdb2f0f3682326954",
            "com.docker.compose.container-number": "1",
            "com.docker.compose.oneoff": "False",
            "com.docker.compose.project": "postgis",
            "com.docker.compose.service": "postgis",
            "com.docker.compose.version": "1.7.0rc1"
        }
...

I can extract an individual label value like this:

docker inspect mycontainer |
jq -r '.[0].Config.Labels["com.docker.compose.project"]'

Which gets me:

postgis
Larry Cai
  • 55,923
  • 34
  • 110
  • 156
larsks
  • 277,717
  • 41
  • 399
  • 399