简体   繁体   中英

Run a docker container from python

I am trying to 'port' this (working) shell command:

IMAGE_NAME="myimage"
CONTAINER_NAME="myname"
docker run -d --name $CONTAINER_NAME $IMAGE_NAME tail -f /dev/null

to start a container from an image to python with:

import subprocess
IMAGE_NAME="myimage"
CONTAINER_NAME="myname"
subprocess.check_output(['docker', 'run',"-d","--name %s" % CONTAINER_NAME,"%s" % IMAGE_NAME])

but if fails with:

unknown flag: --name myname
See 'docker run --help'.

Any suggestions?

Docker has its python library exposing the Docker API so you can work with containers in a programmatic way, calling methods on them, etc.

https://github.com/docker/docker-py

If you want to stick to the subprocess way, you need to put each argument to a separate element in the list you pass to check_output() . Note that arguments are separated by a whitespace, regardless of whether one argument is a value to a switch, like in --name name - those are still two arguments. Of course, if arguments are grouped in quotes, eg --name "a name" , then the whole a name part would be a single element in the subprocess call.

Everywhere that you put a space in the arguments should be a different element in the list. It thinks that "--name myname" is a single flag. Have you tried:

subprocess.check_output(['docker', 'run', '-d', '--name', CONTAINER_NAME, IMAGE_NAME])

Piece of code bellow based on https://github.com/docker/docker-py library

import docker
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
container = client.containers.run('28_googleplay_root_x86_64:latest', name='your_name', detach=True, ports={'5556/tcp': 5556, '5555/tcp': 5555}, devices=['/dev/kvm'])

Container will be created and detached. Library documentation can be find here https://docker-py.readthedocs.io/en/stable/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM