Docker Community Forums

Share and learn in the Docker community.

Get the container name

HI, how to get the container name in a running container (container name: docker run --name test1)

If you can settle for the container ID.

🐳  gforghetti:[~] $ docker container exec -it test1 awk -F'/' 'NR==1 {print $3}' /proc/self/cgroup
2b3072cae52d3579f2d3b12a967e6b6dace6be7231c4ed4722f66e2435229910

in your docker run command, you can also define the “–hostname test1”, this will define the hostname IN THE container :slight_smile:

You can also set an environment variable passed to your container (–env MY_CONTAINER_NAME=“TEST1”).

There is no standard way (provided by Docker) to get the container name. There are a few workarounds:

  1. provide the container name as an environment variable (or argument variable). Eg docker run -e ctnName=X
  2. set the hostname from random character to the container name, then we retrieve it with hostname command
  3. retrieve the name via DNS. Eg, in Swarm with a network overlay, you can do nslookup [Ip] and the Docker DNS will provide the container name, appended by the network name.
  4. ask docker via docker socket 2375/tcp. Not secure, very dirty.