Clearing the Docker cache is an essential task when you want to ensure that your Docker builds are up-to-date and not relying on outdated layers. Here’s a step-by-step guide on how to clear Docker cache:
Step 1: List Docker Images
Before you clear the Docker cache, it’s a good practice to list all the Docker images currently present on your system. You can do this by running:
This command will display a list of all Docker images along with their tags and sizes.
Step 2: Clear the Cache
There are a couple of methods you can use to clear the Docker cache:
Method 1: Using
docker system prune (Recommended)
The easiest way to clear the Docker cache, as well as other unused resources like stopped containers and dangling images, is to use the
docker system prune command. Open your terminal and run:
docker system prune -a
-a flag removes all unused images, not just the dangling ones. Confirm the action by typing ‘y’ when prompted.
Method 2: Removing Specific Images
If you want to clear the cache for specific images, you can do so by removing those images. First, list the images you want to remove using the
docker images command, and then remove them one by one or in bulk using
# List images docker images # Remove a single image docker rmi <image_id> # Remove multiple images (replace <image_id> with the actual IDs) docker rmi <image_id_1> <image_id_2>
Step 3: Verify
After clearing the cache using either method, you can re-run
docker images to verify that the cache has been cleared, and the images you wanted to remove are no longer present.
Step 4: Build Your Docker Images
Now that you’ve cleared the Docker cache, you can build your Docker images as needed. Docker will start from scratch, ensuring that you’re using the latest versions of your dependencies and not relying on cached layers.
In summary, clearing the Docker cache is a straightforward process that can help you avoid issues related to outdated layers and manage your Docker images more effectively. Using the
docker system prune command is the recommended way to clear the cache as it also takes care of other unnecessary resources, but you can also manually remove specific images if needed.