将docker run转换为python docker,传递环境变量的问题

时间:2020-02-28 19:04:44

标签: docker python-docker

我正在尝试将以下docker run命令转换为python docker run:

docker run -v ${HOME}/mypath/somepath:/root/mypath/somepath:ro -v /tmp/report/:/root/report -e MY_VAR=fooname DOCKER_IMAGE

这就是我到目前为止所拥有的:

client = docker.from_env()
client.containers.run(DOCKER_IMAGE, 'MY_VAR=fooname', volumes={
    f'{home}/mypath/somepath': {'bind': '/root/mypath/somepath', 'mode': 'ro'},
    '/tmp/report': {'bind': '/root/report', 'mode': 'rw'},
},)

但是似乎在传递env变量时遇到了问题

docker.errors.APIError: 500 Server Error: Internal Server Error ("OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"MY_VAR=fooname\": executable file not found in $PATH": unknown")

传递环境变量的正确方法是什么?

编辑

更改为

client.containers.run(DOCKER_IMAGE, None, environment=['MY_VAR=fooname'], volumes={
    f'{home}/mypath/somepath': {'bind': '/root/mypath/somepath', 'mode': 'ro'},
    '/tmp/report': {'bind': '/root/report', 'mode': 'rw'},
},)

我收到此错误:docker.errors.ContainerError: Command 'None' in image

docker构建文件具有声明为仅运行python脚本的命令。

1 个答案:

答案 0 :(得分:0)

run()方法的第二个参数是命令,而不是环境。如果您没有命令,请传递None

根据文档,environment必须是字典或列表,所以在您的情况下:

client.containers.run(DOCKER_IMAGE, None, environment=['MY_VAR=fooname'], ...

文档:https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.ContainerCollection.run