简体   繁体   English

docker-compose 从容器内部获取容器名称

[英]docker-compose get Container Name from inside of the Container

How do I get the Name of a container from inside that container in docker-compose?如何从 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).我需要名称,因为它需要相同,即使服务停止并稍后重新启动(意味着 ID 不够用)。 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).我还需要为容器的每个实例使用不同的名称(因为我需要能够在缩放时区分容器)。

Instead of using an auto generated container-name, you can define the name of the container in your docker-compose file, see the docs :您可以在 docker-compose 文件中定义容器名称,而不是使用自动生成的容器名称,请参阅文档

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-compose动态获取容器名称,您可以执行以下命令。

$(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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM