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

查看:27
本文介绍了使用 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'

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

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

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

解决方案

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.

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

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

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"

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'"

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天全站免登陆