Variabel di Dockerfile

Pengantar Docker

Tim Sangster

Software Engineer @ DataCamp

Variabel dengan instruksi ARG

Buat variabel di Dockerfile

ARG <var_name>=<var_value>

Contoh ARG path=/home/repl

Untuk digunakan di Dockerfile

$path

Contoh COPY /local/path $path

Pengantar Docker

Kasus penggunaan instruksi ARG

Mengatur versi 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

Mengonfigurasi folder

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

Menetapkan variabel ARG saat build time

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

Menetapkan variabel di perintah build

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

ARG ditimpa, dan file berakhir di:

COPY /local/project/files /repl/pipeline
COPY /local/project/test_files /repl/pipeline/tests
Pengantar Docker

Variabel dengan ENV

Buat variabel di Dockerfile

ENV <var_name>=<var_value>

Contoh ENV DB_USER=pipeline_user

Untuk digunakan di Dockerfile atau saat runtime

$DB_USER

Contoh CMD psql -U $DB_USER

Pengantar Docker

Kasus penggunaan instruksi ENV

Menetapkan direktori untuk digunakan saat runtime

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

Menetapkan atau mengganti variabel saat 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
Pengantar Docker

Rahasia dalam variabel tidak aman

docker history <image-name>

ARG DB_PASSWORD=example_password

Akan terlihat di docker history:

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

Ringkasan

Penggunaan Instruksi Dockerfile
Buat variabel yang hanya dapat diakses saat build ARG <name>=<value>
Buat variabel ENV <name>=<value>

Penggunaan Perintah Shell
Menimpa ARG saat docker build docker build --build-arg <name>=<value>
Menimpa ENV saat docker run docker run --env <name>=<value> <image-name>
Lihat instruksi yang digunakan untuk membuat image docker history <image-name>
Pengantar Docker

Ayo berlatih!

Pengantar Docker

Preparing Video For Download...