我试图在一个已经运行的容器上使用 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 命令。您只能在容器内运行的 bash 之类的 shell 中使用它。
此外,您尝试实现的目标(设置环境变量)将无法正常工作。一旦您的 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)
关于python - 使用 docker-py 执行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560642/