docker-compose get Container Name from inside of the Container

Viewed 447

How do I get the Name of a container from inside that container in docker-compose?

I need the name, because it needs to be the same, even if the service is stopped and later restared (meaning that the ID will not suffice). I also need a different name for each instance of the container (because I need to be able to differentiate the containers when they were scaled).

2 Answers

Instead of using an auto generated container-name, you can define the name of the container in your docker-compose file, see the docs:

container_name
Specify a custom container name, rather than a generated default name.

container_name: my-web-container

If you want to get the container name dynamically by docker-compose you can execute the below command.

$(docker inspect -f '{{.Name}}' $(./devbox docker-compose ps -q web) | cut -c2-)

If you want to get the container name within the container then can execute the below command.

cat /proc/self/cgroup | grep "cpu:/" | sed 's/\([0-9]\):cpu:\/docker\///g'

Related