Variables dans les Dockerfiles

Introduction à Docker

Tim Sangster

Software Engineer @ DataCamp

Variables avec l'instruction ARG

Créer des variables dans un Dockerfile

ARG <var_name>=<var_value>

Par exemple : ARG path=/home/repl

Utilisation dans le Dockerfile

$path

Par exemple : COPY /local/path $path

Introduction à Docker

Cas d'usage de l'instruction ARG

Définir la version de Python

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

Configurer un dossier

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

Définir des variables ARG au moment du build

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

Définir une variable dans la commande de construction

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

ARG est remplacé, et les fichiers se retrouvent dans :

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

Variables avec ENV

Créer des variables dans un Dockerfile

ENV <var_name>=<var_value>

Par exemple : ENV DB_USER=pipeline_user

Utilisation dans le Dockerfile ou à l'exécution

$DB_USER

Par exemple : CMD psql -U $DB_USER

Introduction à Docker

Cas d'usage de l'instruction ENV

Définir un répertoire utilisé à l'exécution

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

Définir ou remplacer une variable à l'exécution

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 à Docker

Les secrets dans des variables ne sont pas sécurisés

docker history <image-name>

ARG DB_PASSWORD=example_password

S'affichera dans docker history :

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

Résumé

Usage Instruction Dockerfile
Créer une variable accessible seulement pendant le build ARG <name>=<value>
Créer une variable ENV <name>=<value>

Usage Commande Shell
Remplacer un ARG dans docker build docker build --build-arg <name>=<value>
Remplacer un ENV dans docker run docker run --env <name>=<value> <image-name>
Voir les instructions utilisées pour créer une image docker history <image-name>
Introduction à Docker

Passons à la pratique !

Introduction à Docker

Preparing Video For Download...