Python script to run docker
<p>Flow of the python script:</p>

<ul>
<li>I want to run docker image from python script. </li>
<li>After running docker image, I need to execute a shell script which creates a tar file inside docker container.</li>
<li>I need to copy that tar file to host machine from docker container.</li>
<li>and then python script should continue with some stuff to be executed on host machine.</li>
</ul>

<p>Using docker-py module, I was able to do following:</p>

<pre><code> pip install docker-py

    docker version
    Client:
     Version:      1.12.1
     API version:  1.24
     Go version:   go1.6.3
     Git commit:   23cf638
     Built:        Thu Aug 18 05:22:43 2016
     OS/Arch:      linux/amd64

    Server:
     Version:      1.12.1
     API version:  1.24
     Go version:   go1.6.3
     Git commit:   23cf638
     Built:        Thu Aug 18 05:22:43 2016
     OS/Arch:      linux/amd64

    &gt;&gt;&gt; import docker

    &gt;&gt;&gt; c = docker.Client(base_url='unix://var/run/docker.sock',version='1.12',timeout=10)

    &gt;&gt;&gt; c.images()
    [{u'Created': 1476217543, u'Labels': {}, u'VirtualSize': 5712315133, u'ParentId': u'sha256:1ba2be8d70b6ede3b68b1af50759e674345236dd952225fcbfbcc1781f370252', u'RepoTags': [u'ubuntu14.04_64:latest'], u'RepoDigests': None, u'Id': u'sha256:1c8ced0fb34d776adafaed938d41a69e3bab87466beaa8752d49bde0d81230c5', u'Size': 5712315133}]

    &gt;&gt;&gt; ctr = c.create_container('ubuntu14.04_64:latest') 

    &gt;&gt;&gt; c.start(ctr)

    docker  ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    d685766385e7        ubuntu14.04_64:latest              "bash"              16 hours ago        Up 16 hours                             focused_fermi

    docker images
    REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
    ubuntu14.04_64               latest              1c8ced0fb34d        21 hours ago        5.712 GB
</code></pre>

<p>I see docker image and container running on host, but now if I want to run shell script inside docker container, how can I do that? after that I need to copy tar from container to host also. Can someone suggest how to do this?</p>

<p>If you want to run a script in a container you should create a <code>Dockerfile</code> which contains that script. An example might look something like this:</p>

<pre><code>FROM ubuntu14.04_64:latest
COPY ./script.sh /code/script.sh
CMD /code/script.sh -o /target/output.tar.gz
</code></pre>

<p>Then your python script would look something like this:</p>

<pre><code>#!/usr/bin/env python
import docker

c = docker.from_env()
c.build('.', image_name)
ctr = c.create_container(image_name, volumes='./target:/target')
c.start(ctr)

# the tarball is now at ./target/output.tar.gz, copy it where you want it
</code></pre>

python python-2.7 docker docker-compose dockerpy