How to delete unused Docker images


To prevent your file system from filling up, one must purge old, unused Docker images.

There are many great references available on the web on how to accomplish this. This is what I have found to be most effective.

The goal is to query all running containers to determine whether an image is currently in use before attempting to delete (or remove) it.

Naturally, as a first step, you should remove all exited containers.

# docker rm -v $(docker ps -a -q -f status=exited)

You may also wish to remove created containers that are not running.

# docker rm -v $(docker ps -a -q -f status=created)

Then you can proceed with the Docker image cleanup.

Command

# for i in `docker images | tail -n +2 | awk '{print $1":"$2}'`; do if [[ `docker ps` != *$i* ]]; then docker rmi $i; fi; done

If you wish to leave specific images (say with the word "httpd" in the image name) untouched, then do the following by adding the grep command with the invert-match (-v) parameter.

# for i in `docker images | tail -n +2 | grep -i -v httpd | awk '{print $1":"$2}'`; do if [[ `docker ps` != *$i* ]]; then docker rmi $i; fi; done

Similarly, if you wish to retain multiple images with different words in the image name (i.e. httpd and nginx), do the following:

# for i in `docker images | tail -n +2 | grep -i -v 'httpd\|nginx' | awk '{print $1":"$2}'`; do if [[ `docker ps` != *$i* ]]; then docker rmi $i; fi; done

Generate random string from Linux command line


Command

Use the following command to generate a random 16 character string with lower and upper case letters and "special" characters.

</dev/urandom tr -dc '0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | head -c16; echo ""

Output

2kQjZ&iHSavVPj&U

If you prefer only eight alphanumeric characters, use:

</dev/urandom tr -dc '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | head -c8; echo ""

TCxvA40s