Reputation: 17032
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
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
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
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