使用docker-py管理docker的方法介绍

作者:简简单单 2016-07-28

因为业务需要,需要使用python来清理一些状态为Dead的Container,当然,我们可以使用docker ps -a 然后过滤状态为dead的容器,现在我们有了一个更好的选择:docker-py

官方文档地址:https://docker-py.readthedocs.io/en/stable/

下面说一下简单的使用:

>>> from docker import Client
>>> cli = Client(base_url='unix://var/run/docker.sock')

然后我们要获取所有的exited和dead的containers


>>> exited_containers = cli.containers(quiet=True, filters={'status':'exited'}) #get all the exited container
>>> dead_containers = cli.containers(all=True, quiet=True, filters={'status':'dead'}) #get all the exited container

然后我们可以看到exited_containers 和 dead_containers,然后我们可以通过循环得到所有的container_id

for container in exited_containers:
    print 'the container id is :', container['Id']

然后我们可以调用删除了

cli.remove_container(container=container['Id'])
 

相关文章

精彩推荐