Build an image to create build cache
In this step, we will build a simple Docker image to create some build cache. Docker build cache is a mechanism that speeds up the build process by reusing layers from previous builds. When you build a Docker image, each instruction in the Dockerfile creates a layer. If an instruction hasn't changed since the last build, Docker can reuse the existing layer instead of rebuilding it.
First, let's create a directory for our project and navigate into it.
mkdir ~/project/docker-cache-demo
cd ~/project/docker-cache-demo
Now, we will create a simple Dockerfile. This Dockerfile will copy a file into the image and then run a command.
nano Dockerfile
Add the following content to the Dockerfile
:
FROM ubuntu:latest
COPY . /app
RUN echo "Hello, Docker Cache!" > /app/message.txt
CMD ["cat", "/app/message.txt"]
Save and close the file.
Next, let's create a simple file that we will copy into the image.
nano message.txt
Add some content to message.txt
:
This is a test message.
Save and close the file.
Now, we will build the Docker image. We will tag the image as cache-demo
.
docker build -t cache-demo .
You will see output indicating that Docker is building the image step by step. Each step corresponds to an instruction in the Dockerfile. Docker will download the ubuntu:latest
image if it's not already present, copy the message.txt
file, and then run the echo
command.
After the build is complete, you can verify that the image was created by listing the available images.
docker images
You should see cache-demo
in the list of images.
Now, let's build the image again without making any changes to the Dockerfile or message.txt
.
docker build -t cache-demo .
This time, you will notice that the build process is much faster. Docker reuses the existing layers from the previous build because the instructions in the Dockerfile and the content of message.txt
have not changed. The output will show "Using cache" for most of the steps. This demonstrates how Docker build cache works to speed up subsequent builds.