bash 动态获取由 docker run 命令创建的正在运行的容器 id/name

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46031522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:26:09  来源:igfitidea点击:

Dynamically get a running container id/name created by docker run command

linuxbashdocker

提问by Nobita

So I'm trying to run the following shell script which requires the container id/name of the container (in which the script would be run) dynamically.

因此,我正在尝试运行以下 shell 脚本,该脚本需要动态获取容器的容器 ID/名称(将在其中运行脚本)。

One way could be to do docker psand then getting the Container Id, but that won't be dynamic.

一种方法可能是执行docker ps然后获取容器 ID,但这不会是动态的。

So is there a way to do this dynamically?

那么有没有办法动态地做到这一点?

#!/bin/bash
docker exec <container id/name> /bin/bash -c "useradd -m <username> -p <password>"

回答by yamenk

You can give your container a specific name when running it using --name option.

您可以在运行时使用 --name 选项为容器指定特定名称。

docker run --name mycontainer ...

Then your exec command can use the specified name:

然后您的 exec 命令可以使用指定的名称:

docker exec -it mycontainer ...

回答by dgo

I just figured out a way to do this that works for this. I'm constantly going into my container in bash, but each time I do it I have to look up the id of the running container - which is a pain in the butt. I use the --filtercommand like so:

我只是想出了一种方法来做到这一点。我经常使用 bash 进入我的容器,但每次我都必须查找正在运行的容器的 ID - 这很麻烦。我--filter像这样使用命令:

docker ps -q --filter="NAME={name of container}"

Then the only thing that's output is the id of the container, which allows me to run:

然后输出的唯一内容是容器的 id,它允许我运行:

docker exec -it $(docker ps -q --filter="NAME={name of container}") bash

which is what I really want to do in this case.

在这种情况下,这就是我真正想做的事情。

You can filter by

你可以过滤

id, name, label, exited, status, ancestor, 
beforesince, volume, network, publishexpose, 
health,isolation, or is-task

The documenation for filter is here. Hope that helps someone.

过滤器的文档在这里。希望能帮助某人。