tftd
tftd

Reputation: 17032

Get docker image digest / hash from within the container

I know it is possible to access the docker api and the following command works just fine:
curl -s --unix-socket /var/run/docker.sock http:/v1.24/containers/$HOSTNAME/json | jq -r '.Image'

However, I would really like avoid exposing the docker.sock to the container itself because it is part of a CI build. Is there any other way of retrieving the container image id / hash (i.e. 2acdef41a0c) from within a container itself without exposing the docker.sock and making a curl request to it?

Maybe something like what's shown here Docker, how to get container information from within the container ?

Upvotes: 14

Views: 7283

Answers (3)

nguaman
nguaman

Reputation: 971

The same as @Shayk response, but using docker SDK (python) https://docker-py.readthedocs.io/

import docker
....
client = docker.from_env()
image_name = "ubuntu:bionic"
image_id = str(client.images.get(image_name).id).split(":")[1][:12]

container = client.containers.run(image_name, 
    network = "host",
    environment=[f"IMAGE_ID={image_id}",f"IMAGE_NAME={image_name}"],
    detach=True)

Upvotes: 0

ShayK
ShayK

Reputation: 429

This sets IMAGE env var inside a container:

docker run --rm -it -e IMAGE=$(docker images ubuntu:bionic --format {{.ID}}) ubuntu:bionic

Upvotes: 3

AmitP
AmitP

Reputation: 437

The following command run inside the container should give you the container ID or the docker image hash- cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3 | cut -c 1-12

Upvotes: -1

Related Questions