如何在 docker 容器中执行命令作为 bash shell 脚本的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36627980/
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
How to execute commands in docker container as part of bash shell script
提问by Patrik Mihal?in
I would like to write a bash script that automates the following:
我想编写一个自动执行以下操作的 bash 脚本:
Get inside running container
进入正在运行的容器
docker exec -it CONTAINER_NAME /bin/bash
Execute some commands:
执行一些命令:
cat /dev/null > /usr/local/tomcat/logs/app.log
exit
The problematic part is when docker exec
is executed. The new shell is created, but the other commands are not executed.
有问题的部分是何时docker exec
执行。创建了新的 shell,但不执行其他命令。
Is there a way to solve it?
有办法解决吗?
回答by anubhava
You can use heredoc
with docker exec
command:
你可以用heredoc
与docker exec
命令:
docker exec -i CONTAINER_NAME bash <<'EOF'
cat /dev/null > /usr/local/tomcat/logs/app.log
exit
EOF
To use variables:
使用变量:
logname='/usr/local/tomcat/logs/app.log'
then use as:
然后用作:
docker exec -i CONTAINER_NAME bash <<EOF
cat /dev/null > "$logname"
exit
EOF
回答by user2915097
You can simply launch
你可以简单地启动
docker exec -it container_id cat /dev/null > /usr/local/tomcat/logs/app.log
docker exec -it container_id cat /dev/null > /usr/local/tomcat/logs/app.log