Skip to content

Instantly share code, notes, and snippets.

@channprj
Last active February 18, 2021 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save channprj/b210a8426af3938cf761c0226f87f984 to your computer and use it in GitHub Desktop.
Save channprj/b210a8426af3938cf761c0226f87f984 to your computer and use it in GitHub Desktop.
Remove dangling container images safely
#!/bin/bash
# naive way
docker system prune -a -f
# ... or
# simple way
if [ $(echo -n $(docker images -f "dangling=true" -q) | wc -m) -gt 0 ]; then docker rmi -f $(docker images -f "dangling=true" -q); else echo "No Dangling container images"; fi
# ... or
# Remove exited containers
EXITED_CONTAINERS=$(docker ps -a -f status=exited -q)
if [ ! -z "${EXITED_CONTAINERS}" ]
then
docker rm ${EXITED_CONTAINERS} &2>1
echo "Remove exited containers."
else
echo "...No exited containers."
fi
# Remove docker dangling images
DANGLING_IMAGES=$(docker images -f dangling=true -q)
if [ ! -z "${DANGLING_IMAGES}" ]
then
docker rmi ${DANGLING_IMAGES} &2>1
echo "Remove dangling images."
else
echo "...No dangling images."
fi
# Remove docker dangling volumes
DANGLING_VOLUMES=$(docker volume ls -f dangling=true -q)
if [ ! -z "${DANGLING_VOLUMES}" ]
then
docker volume rm ${DANGLING_VOLUMES} &2>1
echo "Remove dangling volumes."
else
echo "...No dangling volumes."
fi
# Remove unused images
docker image prune -a -f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment