0

I want to write a python script that run docker containers and then show logs for that particular container, I have use some functions that are working and starting or stoping containers for me. Can somebody help me to show logs for the containers ?? I tried to use container.logs() function, but it is not working for me, i am also trying to study docker-py library ! I don't know much about python, any help will be highly appreciated !

#!/usr/bin/python
import docker
c = docker.Client(base_url='unix://var/run/docker.sock',version='1.12',timeout=10)
ctr = c.create_container('ubuntu:16.04') 
c.start(ctr)
Saad
  • 916
  • 1
  • 15
  • 28

2 Answers2

4

You are using a old docker client. Run below to fix that

pip uninstall docker-py
pip install docker

Once done you can use something like below

import docker

c = docker.DockerClient(base_url='unix://var/run/docker.sock',timeout=10)
ctr = c.containers.run('ubuntu:16.04',command="bash -c ' for((i=1;i<=10;i+=2)); do echo Welcome $i times; sleep 10; done'", detach=True) 
logs = ctr.logs(stream=True)

for line in logs:
    print(line)
Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
  • Not running properly, will you please help a little ! ======>> Traceback (most recent call last): File "pydoc.py", line 3, in c = docker.DockerClient(base_url='unix://var/run/docker.sock',timeout=10) AttributeError: 'module' object has no attribute 'DockerClient' <============ – Saad Sep 11 '17 at 10:56
  • That means you still are on old client – Tarun Lalwani Sep 11 '17 at 11:05
  • Tarun, i have upgraded all the packages ... using this but still getting this error ! i have upgrade it using, `pip install --upgrade docker-py` `pip install --upgrade docker` – Saad Sep 11 '17 at 11:29
  • yes obviously i have first uninstalled it then i have again installed it ! But still it is not working fine ! – Saad Sep 11 '17 at 11:40
  • Please test it in a fresh new virtual environment, the code has been tested on my end and then only shared. The code has nothing wrong. Please us https://virtualenvwrapper.readthedocs.io/en/latest/ – Tarun Lalwani Sep 11 '17 at 11:42
1

@Tarun , i come through it and it solved my problem , its easy ! by the way thanks for your help man !

import docker
import dockerpty

client = docker.Client()
container = client.create_container(
image='busybox:latest',
   stdin_open=True,
   tty=True,
   command='/bin/sh',
)
client.start(container)
dockerpty.PseudoTerminal(client, container).start()
Saad
  • 916
  • 1
  • 15
  • 28