get docker container name from within the container

i recently needed to know the container's own name from within the container. by default the hostname of the container is set to the short container ID but not to the name. I was working with docker-compose which creates a “nice” name for our containers and i needed that name.

many solutions you find on the internet suggest to share the docker unix socket or tcp socket to access this information from within the container, but that's extremely dangerous as it allows full control over your docker and therefore over your host system with just a few steps from within the container..

here is a much simpler and better way i have found: we simply query the embedded DNS from docker :)

host $(host $(hostname) | awk '{print $NF}') | awk '{print $NF}' | awk -F . '{print $1}'

this worked for me :)

  • get_docker_container_name_from_within_the_container.txt
  • Last modified: 16.06.2021 13:01
  • by Pascal Suter