How to Remove a Docker Image
TLDR
Use docker rmi <image>
to remove a Docker image. If the image is in use by a container, stop and remove the container first. Use docker image prune
to clean up dangling images.
Docker images can pile up quickly, especially during development or CI/CD runs. Removing unused images helps free up disk space and keeps your environment tidy.
Why Remove Docker Images?
- Save Disk Space: Old images can consume gigabytes of storage.
- Reduce Clutter: Fewer images make it easier to manage and find what you need.
- Avoid Conflicts: Outdated images can cause version mismatches.
Listing Images
Before removing, list your images to see what's available:
docker images
This shows all images, their tags, and IDs.
Removing a Specific Image
To remove an image by name or ID:
# Remove by name
docker rmi nginx:alpine
# Remove by image ID
docker rmi 1a2b3c4d5e6f
If the image is used by a container, you'll see an error. Stop and remove the container first:
docker ps -a # Find the container using the image
docker stop <container_id>
docker rm <container_id>
docker rmi <image>
Removing Dangling and Unused Images
Dangling images are layers not tagged or referenced by any container. Clean them up with:
docker image prune
To remove all unused images (not just dangling):
docker image prune -a
Note: This command will remove all images not currently used by any container, so use it with caution.
Best Practices
- Regularly clean up unused images, especially on CI/CD runners.
- Use tags to keep track of image versions.
- Automate cleanup with scheduled jobs if needed.
By managing your Docker images proactively, you keep your development environment fast and reliable.
Good luck with your project!
Found an issue?