批量删除docker容器和镜像

有时候启动了多个容器或是构建了多个镜像,会导致存在多个无用的容器和镜像,一个一个删除的话太费劲,想要实现批量删除,借助于grep和awk工具,我们可以轻松实现这个目的

例如:

1
2
3
4
5
6
7
8
9
10
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
13563a04bb6a odoo:qunar "/entrypoint.sh open…" 44 hours ago Exited (255) 12 minutes ago 0.0.0.0:8069->8069/tcp, 8071/tcp inspiring_jang
fa1ee76c7261 odoo:qunar "/entrypoint.sh open…" 44 hours ago Created optimistic_leavitt
aebb10ced752 be7df4762b94 "/entrypoint.sh open…" 44 hours ago Exited (0) 44 hours ago amazing_bhabha
a432735ce166 be7df4762b94 "/entrypoint.sh open…" 44 hours ago Created sharp_pasteur
63bece7c8bc1 817de5cdbd08 "/entrypoint.sh open…" 44 hours ago Exited (0) 44 hours ago optimistic_stonebraker
737e3321ce5e fd41c1224def "/bin/sh -c 'apt-get…" 44 hours ago Exited (1) 44 hours ago wonderful_panini
4481a015c6eb a9cbf361b39e "/entrypoint.sh open…" 45 hours ago Exited (0) 44 hours ago laughing_euler
9a6f8823eeba e83 "/entrypoint.sh odoo" 3 days ago Exited (137) 2 days ago odoo10e
681c7db9d75e 23c "/entrypoint.sh odoo" 3 days ago Exited (0) 3 days ago odoo10

存在多个container,想要保留odoo相关的容器,而删除其他无用的容器,可使用下面的命令:

1
docker rm `docker ps -a | grep -v 'odoo' |awk '{print $1}'`

再例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
root@venus:/home/kevin/codes# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
odoo qunar 3a4a40aadd32 44 hours ago 813MB
kevinkong/odoo qunar 3a4a40aadd32 44 hours ago 813MB
kevinkong/odoo <none> be7df4762b94 45 hours ago 813MB
<none> <none> 817de5cdbd08 45 hours ago 1.03GB
<none> <none> a9cbf361b39e 45 hours ago 1.01GB
<none> <none> 0b3555aabbf3 45 hours ago 742MB
<none> <none> eb03fdc57fd9 45 hours ago 114MB
odoo v8 0f7422de5013 46 hours ago 742MB
<none> <none> 94f880258a54 46 hours ago 742MB
<none> <none> f7af934b7a01 47 hours ago 742MB
<none> <none> 88e8eaf89647 47 hours ago 742MB
<none> <none> 131e637d520a 47 hours ago 742MB
<none> <none> 12ba63a4471f 47 hours ago 742MB
<none> <none> f52ae88b0c3c 2 days ago 742MB
flask_order test f9229334fe7a 2 days ago 1.15GB
kevinkong/odoo v10e e834d58329c2 3 days ago 1.11GB
odoo v10e e834d58329c2 3 days ago 1.11GB
kevinkong/odoo v10 23c958989020 4 days ago 1.01GB
odoo v10 23c958989020 4 days ago 1.01GB
python 3.6 d330010a503a 5 days ago 912MB
registry.docker-cn.com/library/python 3.6 d330010a503a 5 days ago 912MB
kevinkong/odoo v8 cc0330013b8b 5 days ago 742MB
ubuntu 16.04 5e8b97a2a082 4 weeks ago 114MB
registry.docker-cn.com/library/ubuntu 16.04 5e8b97a2a082 4 weeks ago 114MB
hello-world latest e38bc07ac18e 2 months ago 1.85kB

想要删除所有包含none的镜像,可使用如下命令:

1
docker rmi `docker images | grep 'none' | awk '{print $3}'`