使用docker exec执行两个命令 [英] Execute two commands with docker exec

查看:904
本文介绍了使用docker exec执行两个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在docker exec中执行两个命令.具体来说,我必须在特定目录中运行命令. 我试过了,但是没用:

I'm trying to do two commands in docker exec. Concretely, I have to run a command inside a specific directory. I tried this, butit didn't work:

docker exec [id] -c 'cd /var/www/project && composer install'

未检测到参数-c. 我也尝试过这个:

Parameter -c is not detected. I also tried this:

docker exec [id] cd /var/www/project && composer install

但是在docker exec命令之后执行命令composer install. 我该怎么办?

But the command composer install is executed after the docker exec command. How can I do it?

推荐答案

在第一个示例中,您将-c标志赋予docker exec.这是一个简单的答案:docker exec没有-c标志.

In your first example, you are giving the -c flag to docker exec. That's an easy answer: docker exec does not have a -c flag.

在第二个示例中,您的shell在Docker甚至没有看到它之前就将其解析为两个命令.等效于此:

In your second example, your shell is parsing this into two commands before Docker even sees it. It is equivalent to this:

if docker exec [id] cd /var/www/project
then
    composer install
fi

首先,运行docker exec,如果退出0(成功),则composer install将尝试在Docker外部本地运行 .

First, the docker exec is run, and if it exits 0 (success), composer install will try to run locally, outside of Docker.

您需要做的是使用字符串将两个命令作为单个参数传递给docker exec.这样一来,除非它们已经在容器中,否则它们不会被外壳解释.

What you need to do is pass both commands in as a single argument to docker exec using a string. Then they will not be interpreted by a shell until already inside the container.

docker exec [id] "cd /var/www/project && composer install"

但是,正如您在评论中指出的那样,这也不起作用.这是因为cd是内置的shell,并不单独存在.尝试将其作为初始命令执行将失败.因此,下一步是将其交给外壳执行.

However, as you noted in the comments, this also does not work. That's because cd is a shell builtin, and doesn't exist on its own. Trying to execute it as the initial command will fail. So the next step is to hand this off to a shell to execute.

docker exec [id] "bash -c 'cd /var/www/project && composer install'"

最后,在这一点上,&&已移到内部引号中,因此我们实际上并不需要bash命令周围的引号...如果愿意,可以将其删除. /p>

And finally, at this point the && has moved into an inner set of quote marks, so we don't really need the quotes around the bash command... you can drop them if you prefer.

docker exec [id] bash -c 'cd /var/www/project && composer install'

这篇关于使用docker exec执行两个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆