Build services with build arguments and no cache
In this step, we will explore two advanced build options with Docker Compose: using build arguments and building without cache.
Build arguments allow you to pass variables to the Docker build process. This is useful for customizing the build based on different environments or configurations without changing the Dockerfile
itself.
First, let's modify our Dockerfile
to accept a build argument. Open the Dockerfile
for editing:
nano ~/project/Dockerfile
Change the content to the following:
FROM ubuntu:latest
ARG MESSAGE="Hello from build argument!"
RUN apt-get update && apt-get install -y cowsay
CMD ["cowsay", "$MESSAGE"]
We have added an ARG MESSAGE
instruction to define a build argument named MESSAGE
with a default value. We also changed the CMD
instruction to use this argument.
Save the Dockerfile
by pressing Ctrl + X
, then Y
, and Enter
.
Now, let's modify our docker-compose.yml
file to pass a value to this build argument. Open the file for editing:
nano ~/project/docker-compose.yml
Change the content to the following:
version: "3.8"
services:
cow:
build:
context: .
args:
MESSAGE: "Custom message from Compose!"
We have changed the build:
directive to an object with context:
and args:
.
context: .
specifies the build context, which is the directory containing the Dockerfile
.
args:
is a map of build arguments to pass to the Dockerfile
. We are passing the value "Custom message from Compose!"
to the MESSAGE
argument.
Save the docker-compose.yml
file by pressing Ctrl + X
, then Y
, and Enter
.
Now, let's build the image with the build argument. Make sure you are in the ~/project
directory.
cd ~/project
docker-compose build
Observe the build output. You should see that the build argument is used during the build process.
After the build is complete, let's run a container from this image to see the output.
docker run project_cow
You should see the cowsay
output with the message "Custom message from Compose!". This confirms that the build argument was successfully passed and used.
Sometimes, you might want to force Docker to rebuild all layers, ignoring the cache. This is useful when you suspect caching issues or want to ensure a clean build. You can do this using the --no-cache
flag with the docker-compose build
command.
Let's try rebuilding the image with the --no-cache
flag.
docker-compose build --no-cache
Observe the build output again. This time, you will see that Docker does not use any cached layers and rebuilds every step in the Dockerfile
. This process will take longer than a cached build.
After the build is complete, you can run the container again to confirm the message is still the one passed via the build argument.
docker run project_cow
You should still see "Custom message from Compose!". The --no-cache
flag only affects the build process, not the configuration defined in docker-compose.yml
.