Variables in Dockerfiles

Introduction to Docker

Tim Sangster

Software Engineer @ DataCamp

Variables with the ARG instruction

Create variables in a Dockerfile

ARG <var_name>=<var_value>

For example ARG path=/home/repl

To use in the Dockerfile

$path

For example COPY /local/path $path

Introduction to Docker

Use-cases for the ARG instruction

Setting the Python version

FROM ubuntu
ARG python_version=3.9.7-1+bionic1
RUN apt-get install python3=$python_version
RUN apt-get install python3-dev=$python_version

Configuring a folder

FROM ubuntu
ARG project_folder=/projects/pipeline_v3
COPY /local/project/files $project_folder
COPY /local/project/test_files $project_folder/tests
Introduction to Docker

Setting ARG variables at build time

FROM ubuntu
ARG project_folder=/projects/pipeline_v3
COPY /local/project/files $project_folder
COPY /local/project/test_files $project_folder/tests

Setting a variable in the build command

docker build --build-arg project_folder=/repl/pipeline .

ARG is overwritten, and files end up in:

COPY /local/project/files /repl/pipeline
COPY /local/project/test_files /repl/pipeline/tests
Introduction to Docker

Variables with ENV

Create variables in a Dockerfile

ENV <var_name>=<var_value>

For example ENV DB_USER=pipeline_user

To use in the Dockerfile or at runtime

$DB_USER

For example CMD psql -U $DB_USER

Introduction to Docker

Use-cases for the ENV instruction

Setting a directory to be used at runtime

ENV DATA_DIR=/usr/local/var/postgres
ENV MODE production

Setting or replacing a variable at runtime

docker run --env <key>=<value> <image-name>

docker run --env POSTGRES_USER=test_db --env POSTGRES_PASSWORD=test_db postgres

1 https://hub.docker.com/_/postgres
Introduction to Docker

Secrets in variables are not secure

docker history <image-name>

ARG DB_PASSWORD=example_password

Will show in docker history:

IMAGE          CREATED        CREATED BY                          SIZE      ...
cd338027297f   2 months ago   ARG DB_PASSWORD=example_password    0B        ...
Introduction to Docker

Summary

Usage Dockerfile Instruction
Create a variable accessible only during the build ARG <name>=<value>
Create a variable ENV <name>=<value>

Usage Shell Command
Override an ARG in docker build docker build --build-arg <name>=<value>
Override an ENV in docker run docker run --env <name>=<value> <image-name>
See the instructions used to create an image docker history <image-name>
Introduction to Docker

Let's practice!

Introduction to Docker

Preparing Video For Download...