10

How can I get docker's container name from inside the container?

I can't use "inspect" because I have to use a script from inside the container to get information from a JSON url.

questionto42
  • 7,175
  • 4
  • 57
  • 90
Mariano DAngelo
  • 920
  • 5
  • 18
  • 39
  • Possible duplicate of [Docker, how to get container information from within the container?](http://stackoverflow.com/questions/20995351/docker-how-to-get-container-information-from-within-the-container) – Jason Nov 08 '16 at 22:33

6 Answers6

10

If you mean the Container ID its available in the env as the hostname variable. It should be interchangeable with the name for most operations.

env
HOSTNAME=5252eb24b296
TERM=xterm
....

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5252eb24b296        ubuntu:14.04        "bash"              23 seconds ago      Up 22 seconds                           test
Usman Ismail
  • 17,999
  • 14
  • 83
  • 165
  • 11
    Though, this way will not work in two cases. First - if hostname is explicitly specified with `--hostname` flag, second - when using `--net=host` mode. – Viacheslav Kovalev Nov 17 '14 at 19:07
  • Also, not if the container name is specified with `--name`. (Assuming that what you want is the friendly name, and not the automatically assigned name). – Dan Tenenbaum Sep 16 '20 at 18:52
8

you can use cut -c9- < /proc/1/cpuset

Ping.Goblue
  • 576
  • 8
  • 12
  • 1
    surprisingly this is the simplest answer which get's what most people might need – Jim Jul 20 '21 at 22:18
8

If you want the container name rather than container id you can do a reverse DNS lookup on eth0 of the container.

dig -x `ifconfig eth0 | grep 'inet' | awk '{print $2}'` +short | cut -d'.' -f1

This gives you the friendly name rather than the id.

UPDATE: Only works if you have ifconfig and dig and other tools installed.

Amir Razmjou
  • 512
  • 6
  • 10
  • One might want to mention this (obviously) only works if ifconfig, dig, etc. are actually installed inside the docker image. Which is often **not** the case, espacially in Alpine-based or stripped-down images. – Potherca Jun 04 '21 at 11:11
6

I think, most reliable way to use combination of --cidfile and -v options.

docker run --cidfile=/tmp/container.id -v /tmp/container.id:/tmp/container.id ${IMAGE}

If you will start container this way, you can read /tmp/container.id from inside of your container.

Viacheslav Kovalev
  • 1,745
  • 12
  • 17
2

if you have docker inside container,
(you need to bind -v /var/run/docker.sock:/var/run/docker.sock)
and the hostname was not modified you can get it via:
docker inspect -f '{{.Name}}' $HOSTNAME

but this solution can be used only in edge cases.

SielaQ
  • 74
  • 2
2

In the case of docker-compose we had a / in front of the hostname so using cut we removed that.

docker inspect -f '{{ .Name }}' "$HOSTNAME" | cut -c 2-
MrAirikr
  • 21
  • 3