How to access docker container metadata from a script running inside a container?

I am trying to figure out if it is possible to read the metadata properties (Labels, in particular) of a container using a bash script.

For example, if there is a Docker file, for example:

FROM busybox LABEL abc = abc_value1 

And, if I create and run the image based on the above file:

 docker build . -t image1 docker run -ti image1 /bin/bash 

Is there a way to access the value of the “abc” label inside the bash shell? If so, how?

+7
bash docker dockerfile
source share
1 answer

To get labels (and something from the remote API), you can pass the socket to the container and use curl> = 7.40 (this is the minimum version that supports the --unix-socket flag) from the container to access the remote API via the socket:

Dockerfile:

 FROM ubuntu:16.04 RUN apt-get update \ && apt-get install curl -y LABEL abc = abc_value1 

Assembly and launch

 docker build -t image1 . docker run -v /var/run/docker.sock:/var/run/docker.sock -it image1 /bin/bash 

Inside the container

 curl --unix-socket /var/run/docker.sock http:/containers/$(hostname)/json 

From here you will have a huge chunk of JSON (similar to docker validation). Then you can use a CLI tool like jq to pry labels.

More information about the docker website: https://docs.docker.com/engine/reference/api/docker_remote_api/#/docker-remote-api

All of the above is not very safe, and environment variables are probably better.

+5
source share

All Articles