How to Remove Docker Images and Containers

0
608
How to Remove Docker Images and Containers

We have installed and play around the docker somewhat. Now let see if some images and containers occupies our disk space unnecessarily, how to remove that from docker. This steps help to remove images and containers from disk and also we can see how to stop/kill docker images and container.

Remove Docker Images

Docker provides “rmi” option to remove a docker image from our disk. Here you can replace <IMAGE ID> with your docker image ID, which you will from #docker images commend.

# docker rmi <IMAGE ID> To make sure the docker image ID, we can use docker images commends.

[root@foxutech ~]# docker images

REPOSITORY   TAG         IMAGE ID           CREATED             SIZE

container8   latest     ca982185a959       22 hours ago       109.9 MB

centos     latest     970633036444       4 days ago         196.7 MB

ubuntu     latest     42118e3df429       12 days ago         124.8 MB

opensuse   latest    ad767707c80c       2 weeks ago         97.74 MB

If you wish to delete all the images in docker, you can use following commend

# docker rmi $(docker images -qf “dangling=true”)

If you want exclude some image while delete multiple images, you could use “grep” to remove all except “image1” and “image2”

# docker rmi $(docker images | grep -v ‘image2\|image1’ | awk {‘print $3’})

Remove Docker Containers

Docker provides “rm” option to remove a docker Container from our disk. Here you can replace <CONTAINER ID> with your docker Container ID, which you will from #docker ps -a commend.

# docker rm <CONTAINER ID>

To list all containers on your system using ps option, but ps will show only running containers. So to view all containers use -a parameter with ps.

# docker ps -a

If you wish to delete all the container in docker, you can use following commend

# docker stop $(docker ps -a -q)

# docker rm $(docker ps -a -q)

Note: Replace kill with stop for graceful shutdown

Additional:

you can remove a single image with:

# docker rmi the_image

However, if you need to remove multiple you could use:

Remove all images

# docker rmi $(docker images -qf “dangling=true”)

Kill containers and remove them:

# docker rm $(docker kill $(docker ps -aq))

Note: Replace kill with stop for graceful shutdown

Remove all images except “my-image”

You could use grep to remove all except my-image and ubuntu

# docker rmi $(docker images | grep -v ‘ubuntu\|my-image’ | awk {‘print $3’})

Delete all docker containers

# docker rm $(docker ps -a -q)

Delete all docker images

# docker rmi $(docker images -q)

#!/bin/bash

IMAGE=$1 if [ “$IMAGE” == “” ] ; then echo “Missing image argument” exit 2fi docker ps -qa -f “ancestor=$IMAGE” | xargs docker rmdocker rmi $IMAGE

NO COMMENTS