Use docker ARGs for conditionals on build
Problem
Run some script on docker build but only on production and not on development.
Solution
Using ARG in Dockerfile and docker-compose.yml. The "main" is an example for production and "main_dev" for development.
Dockerfile:
FROM python:3 ARG DEV RUN if [ ! "$DEV" = "yes" ]; then echo "DEV is NOT set"; else echo "DEV is set"; fi CMD [ "echo", "OK" ]
docker-compose.yml:
Now lets run the examples:
docker-compose build --no-cache main
results in
Building main Step 1/4 : FROM python:3 ---> 1f88553e8143 Step 2/4 : ARG DEV ---> Running in a369f15bdbba Removing intermediate container a369f15bdbba ---> d33834a028c4 Step 3/4 : RUN if [ ! "$DEV" = "yes" ]; then echo "DEV is NOT set"; else echo "DEV is set"; fi ---> Running in c47c9d3ae979 DEV is NOT set Removing intermediate container c47c9d3ae979 ---> d93839918c95 Step 4/4 : CMD [ "echo", "OK" ] ---> Running in 1280176dc942 Removing intermediate container 1280176dc942 ---> ac023ae1b6fa Successfully built ac023ae1b6fa Successfully tagged dockerarg_main:latest
and
docker-compose build --no-cache main_dev
results in
Building main_dev Step 1/4 : FROM python:3 ---> 1f88553e8143 Step 2/4 : ARG DEV ---> Running in a9bbe1cbf494 Removing intermediate container a9bbe1cbf494 ---> f28af462f46a Step 3/4 : RUN if [ ! "$DEV" = "yes" ]; then echo "DEV is NOT set"; else echo "DEV is set"; fi ---> Running in 908227c7de9c DEV is set Removing intermediate container 908227c7de9c ---> 4f4caad6140a Step 4/4 : CMD [ "echo", "OK" ] ---> Running in 0f83a6b15abf Removing intermediate container 0f83a6b15abf ---> 19bf8758a2ae Successfully built 19bf8758a2ae Successfully tagged dockerarg_main_dev:latest
This seems to work as seen with DEV is NOT set
vs DEV is set
.