Docker Build Arguments
Related Posts
What Are Build Arguments?
Before going into build arguments, it is worth clarifying the difference between arguments and environment variables as they overlap quite a lot.
Build arguments are variables for the sole purpose of building your image. Environment variables may be used to in various ways to help you in building your image, but their main purpose is to pass information to your container when it is being run (after it has been built).
This diagram from a post on vsupalov.com explains it best:
Declaring Build Args In The Dockerfile
You can specify ARG
as part of your Dockerfile
at the start (above the FROM
statement), in
order to declare the arguments your build needs.
These can then be used later as part of the build. E.g.
ARG ACCOUNT_ID
FROM ubuntu:latest
RUN echo $ACCOUNT_ID
Default Value
In the previous example, we required the ACCOUNT_ID
to be provided, but we could specify a
default value that would be overridden, like so:
ARG ACCOUNT_ID="def"
FROM ubuntu:latest
RUN echo $ACCOUNT_ID
Specifying Build Arguments
In order to provide the build arguments, one can provide them in a variety of ways outlined below:
Docker Build Command
One can specify the build arguments at the point of calling the build like so:
#!/bin/sh
docker build \
--build-arg ACCOUNT_ID=abc \
--build-arg SECOND_BUILD_ARG=admin \
...
Docker-compose Command
If using docker-compose build
instead of docker build
, then one would specify the build
arguments in the same manner like so:
docker-compose build \
--build-arg ACCOUNT_ID=abc \
--build-arg SECOND_BUILD_ARG=admin
Docker Compose FIle
The build arguments can also be specified in the docker-compose file like so:
version: '3'
services:
app:
build:
context: .
args:
- ACCOUNT_ID=abcd
First published: 21st August 2022