Communicating with docker engine to get the container name at runtime

Hi All,

I’m trying access the container name at runtime in my startup script in order to improve telemetry from my container.

In order to do this, my container needs to be aware of its name at runtime. Is there a way to dynamically set the container name as a runtime environment variable (via docker run -e or docker-compose for example)?

Otherwise, is it possible for the container to find its own name by communicating with the docker engine? I’ve looked at this stackoverflow question and it looks like it’s possible to get the container name via the docker engine api using the container id which is available by default via powershell as $env:COMPUTERNAME. The stackoverflow post gives ways to do this on linux containers but I haven’t found out how to do this via powershell on windows containers.

1 Like

docker run -e name=foobar

then inside there will be an environment variable set, name=foobar

You could pass the container name either via environment variable or hostname when you create the container. Like this:
docker run -h evmurphy1 -e “containername=evmurphy1” microsoft/nanoserver

You will be able to access the name in PowerShell via $env:COMPUTERNAME (this comes from the -h) or $env:containername (this comes from the -e). Use either one.

Also, in some scenario, you can ask docker own DNS for its container name. This would let you have the container name when this is generated by docker-compose.
nslookup
let you known the container name in the context of the attached network.

if no name was assigned, then the the local name is the container id.