Docker – how to get hostname of the container/Docker host machine

Docker container by default does not allow to peak into the host machine as it is ensures that the container does not have a specifically tied to the host machine. The principle is to have a docker that can run in any host machine. This allows to failover the docker to any machine.

However, there are cases where a docker may need to know where it is running as a part of alerting. In such case, there are two ways to get the host machine name

  1. Map /etc/ to a volume in the docker. Then, /etc/hosts can be read by application
  2. As a part of docker run, an environment name can be created by doing cat on the /etc/hostname for example:
docker run -it -e "HOSTNAME=$(cat /etc/hostname)" <image> <cmd>