0

I have a shell script inside my docker container called test.sh. I would like to pipe the output of this script to a file. I can do this using docker exec command or by logging into the shell (using docker run -it) and running ./test.sh > test.txt. However, I would like to know how the same result can be achieved using the docker sdk for python. This is my code so far:

import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True, working_dir='/home/psr', \
volumes=['/home/psr/data'], \
host_config=client.create_host_config(binds={
    '/home/xxxx/data_generator/data/': {
        'bind': '/home/psr/data',
        'mode': 'rw',
    },

})
)


client.start(container=container.get('Id'))
cmds= './test.sh > test.txt'
exe=client.exec_create(container=container.get('Id'), cmd= cmds, 
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

for val in exe_start:
    print (val)

I am using the Low-Level API of the docker sdk. In case you know how to achieve the same result as above using the high level API, please let me know.

Matt
  • 68,711
  • 7
  • 155
  • 158
Vishnu
  • 499
  • 1
  • 5
  • 23
  • Best practice is for your `test.sh` to send its output to stdout you can then use the `docker log` API capture it. – stacksonstacks Nov 16 '17 at 02:46
  • Do you want the output inside the container or on the docker host? – Matt Nov 16 '17 at 06:42
  • @Matt I would like to write it to a file that is saved on a mounted volume which both the host and docker container has access to. In this question that refers to the directory /home/psr/data inside the container. – Vishnu Nov 16 '17 at 11:12
  • @stacksonstacks I am not sure how I could do that. Could you give me an example with a code snippet? – Vishnu Nov 16 '17 at 11:47

1 Answers1

0

In case anyone else had the same problem, here is how I solved it. Please let me know in case you have a better solution.

import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True, 
working_dir='/home/psr', \
 volumes=['/home/psr/data'], \
 host_config=client.create_host_config(binds={
 '/home/xxxx/data_generator/data/': {
    'bind': '/home/psr/data',
    'mode': 'rw',
},

})
)


client.start(container=container.get('Id'))
cmds= './test.sh'
exe=client.exec_create(container=container.get('Id'), cmd=cmds, 
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

with open('path_to_host_directory/test.txt', 'wb') as f: # wb: For Binary Output
    for val in exe_start:
        f.write(val)
Vishnu
  • 499
  • 1
  • 5
  • 23