Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting docker container using python script

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

like image 581
DevanDev Avatar asked Nov 22 '17 11:11

DevanDev


People also ask

How do I start a docker container?

Start an app container To do so, you will use the docker run command. You use the -d flag to run the new container in “detached” mode (in the background). You also use the -p flag to create a mapping between the host's port 3000 to the container's port 3000.

How do I keep a Python docker container running?

The simplest way to keep the container running is to pass a command that never ends. We can use never-ending commands in any of the following ways: ENTRYPOINT or CMD directive in the Dockerfile. Overriding ENTRYPOINT or CMD in the docker run command.


1 Answers

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, ..).

like image 124
Christian Berendt Avatar answered Oct 09 '22 16:10

Christian Berendt