[英]Executing shell command using docker-py
我正在尝试在已经运行的容器上使用 docker-py 运行 shell 命令,但出现错误:
exec: "export": executable file not found in $PATH
这是我编写脚本的方式:
exe = client.exec_create(container=my_container, cmd='export MYENV=1')
res = client.exec_start(exec_id=exe)
所以我的问题是如何使用 docker-py 运行 shell 命令(在容器内)?
你做得很对。 但是您将 shell 命令与 linux 可执行文件混淆了。 exec_create
和exec_start
都是关于运行可执行文件的。 例如 bash。 您的示例中的export
是一个 shell 命令。 您只能在容器内运行的 shell(如 bash)中使用它。
此外,您试图实现的目标(设置环境变量)不会起作用。 一旦您的 exec 完成(您设置 env var 的位置),exec 进程将完成并且其环境被拆除。
您只能在创建容器时创建全局容器环境变量。 如果要更改环境变量,则必须拆除容器并使用新变量重新创建它。 您可能知道,除非您使用卷来存储数据,否则容器中的所有数据都会在删除时丢失。 在创建容器时重新连接卷。
那就是说你的例子几乎是正确的。 这应该可以工作并创建一个空的/somefile。
exe = client.exec_create(container=my_container, cmd=['touch', '/somefile'])
res = client.exec_start(exec_id=exe)
要执行 shell 命令,请使用此示例。 它调用 sh 并告诉它在给定的命令字符串上运行解释器 (-c)
exe = client.exec_create(container=my_container,
cmd=['/bin/sh', '-c', 'touch /somefile && mv /somefile /bla'])
res = client.exec_start(exec_id=exe)
实际上,在 docker 容器export MYENV=1
中执行 cmd docker docker exec
时。 它将失败并报告此错误
exec: "export": executable file not found in $PATH
因为 export 是内置的 shell,所以可以在 shell 中运行 cmd。
whereis export
type export
在/usr/bin/
或其他地方找不到export
。
有一些方法可以解决这个问题。
case1:使用-c
参数
/bin/bash -c 'export MYENV=1 ; /bin/bash'
case2:将导出命令附加到 rcfile,然后使用此文件。
echo "exprot MYENV=1" >> <some_file_path> ; /bin/bash --rcfile <some_file_path>
case3:打开一个终端,然后输入cmds导出env参数,然后打开一个新的终端,env参数就可以了。
/bin/bash
exprot MYENV=1
/bin/bash # open a new terminal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.