17

I would like to start the docker container from a python script. When i call the docker image through my code , i am unable to start the docker container

import subprocess
import docker


from subprocess import Popen, PIPE


def kill_and_remove(ctr_name):
    for action in ('kill', 'rm'):
        p = Popen('docker %s %s' % (action, ctr_name), shell=True,
                  stdout=PIPE, stderr=PIPE)
        if p.wait() != 0:
            raise RuntimeError(p.stderr.read())


def execute():
    ctr_name = 'sml/tools:8' # docker image file name
    p = Popen(['docker', 'run', '-v','/lib/modules:/lib/modules',
               '--cap-add','NET_ADMIN','--name','o-9000','--restart',
               'always', ctr_name ,'startup',' --base-port',
               9000,' --orchestrator-integration-license',
               ' --orchestrator-integration-license','jaVl7qdgLyxo6WRY5ykUTWNRl7Y8IzJxhRjEUpKCC9Q='
               ,'--orchestrator-integration-mode'],
              stdin=PIPE)
    out = p.stdin.write('Something')

    if p.wait() == -20:  # Happens on timeout

        kill_and_remove(ctr_name)

    return out

following are docker container details for your reference

dev@dev-VirtualBox:sudo docker ps -a
[sudo] password for dev: 
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS              PORTS               NAMES
79b3b9d215f3        sml/tools:8   "/home/loadtest/st..."   46 hours ago        Up 46 hours                             pcap_replay_192.168.212.131_9000_delay_dirty_1

Could some one suggest me why i could not start my container through my program

1 Answer 1

30

docker-py (https://github.com/docker/docker-py) should be used to control Docker via Python.

This will start an Ubuntu container running sleep infinity.

import docker

client = docker.from_env()
client.containers.run("ubuntu:latest", "sleep infinity", detach=True)

Have a look at https://docker-py.readthedocs.io/en/stable/containers.html for more details (capabilities, volumes, ..).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply, i know docker-py, it looks complicated, i used simple subprocess.Popen for running docker container, could you please let me know what is wrong within my code
I am getting following error when i run it through docker_py : raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: UnixHTTPConnectionPool(host='localhost', port=None): Max retries exceeded with url: /v1.30/containers/create (Caused by <class 'socket.error'>: [Errno 13] Permission denied)
[Errno 13] Permission denied. Add your user to the docker group.
how can i add the user to the docker group?#

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.