Search code examples
dockerpython-docker

Converting docker run to python docker, issues passing environmental variables


I'm trying to convert the following docker run command to python docker run:

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

and this is what I have so far:

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'},
},)

But it seems like I'm running into issues when passing the env variables

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

What's the right way to pass the env variables?

EDIT

After changing it to

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'},
},)

I'm getting this error instead: docker.errors.ContainerError: Command 'None' in image

The docker build file has the command declared to just run a python script.


Solution

  • The second parameter of the run() method is the command, not the environment. If you don't have a command then pass None.

    According to the documentation the environment must be either a dict or a list, so in your case:

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

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