Docker-py 的使用

Docker SDK for Python

A Python library for the Docker Engine API

具体文档这里,https://docker-py.readthedocs.io/en/stable/index.html

先说明一下,需求是通过python 调用docker daemon,做到启动一个人服务或者容器,去运行一个程序。

话不多说,先贴上使用容器部分的代码

import docker

cli = docker.from_env()  # 使用本地的docker deamon
py_container = cli.containers.run( #运行一个容器
image='python:3',
command='python hello.py',
volumes={'/opt/':{'bind':'/opt','mode':'rw'}},
name='helloworld-dockerpy1',
working_dir='/opt',
detach=True,
stdout=True,
stderr=True,
user='root',
remove=False
)
def wait_container(): #判断容器退出后,提取log
if py_container in cli.containers.list(filters={'status':'exited'}):
with open('/tmp/py_log.txt', 'a') as f:
f.write(str(py_container.logs()))
else:
wait_container() wait_container()
print(str(py_container.logs()))
py_container.remove()
下面是使用服务的部分代码

还没有解决判断service中容器状态的参数,还在学习APIClient这个调用本地docker daemon的方法。如有大神,请留言教导我。

import docker

cli = docker.from_env()

py_service = cli.services.create(
image='python:3',
name='py_service1',
command='python hello.py',
mounts={'/opt:/opt:rw'},
workdir='/opt',
user='root'
)
time.sleep(30)
logs = py_service.logs(stdout='True')
for l in logs:
len1 = len(l)
if len1 == 0:
print('null')
else:
print(len1)
print(str(l,encoding='utf-8'))
py_service.remove()

下面这段是从本地的docker日志存放目录中提取日志,相对于上一种,这种方法很大弊端在于使用service的使用,容器是运行在swarm中的,不一定就运行在本地的swarm节点上。这样就无法提取日志了。

import docker
import time cli = docker.from_env()
py_service2 = cli.services.create(
image='python:3',
name='py_service2',
command='python hello.py',
mounts={'python_test:/opt:rw'},
workdir='/opt',
user='root'
) time.sleep(10)
def service_log():
attempts = 100
while True:
if attempts == 0:
print('No service logs produced by endpoint')
return
logs = py_service2.logs(stdout='True')
try:
log_line = next(logs)
except StopIteration:
attempts -= 1
time.sleep(0,1)
continue
else:
break
def print_log():
i = 0
while i < 2:
i+=1
list = py_service2.tasks(filters={'desired-state':'shutdown','name':'py_service2'})
logs = py_service2.logs(stdout='True')
time.sleep(5)
container_id = list[0]['Status']['ContainerStatus']['ContainerID']
print(container_id)
container_log = '/var/lib/docker/containers/'+ container_id +'/'+container_id + '-json.log'
all_the_text = open(container_log).read()
print(all_the_text) print_log()
py_service2.remove()
上一篇:[转帖]Nginx rewrite模块深入浅出详解


下一篇:WIN2008中部署网站后样式及JS加载不了