Dockerfile if else condition with external arguments
Codemia Knowledge Hub ·
Dockerfiles have no if-else instruction, but you can get the same result with a shell if inside a RUN instruction that tests a build argument. Declare the argument with ARG, pass it with docker build --build-arg, and the branch runs at build time.
Why a Dockerfile needs the shell for conditionals
A Dockerfile is a list of instructions (FROM, COPY, RUN, CMD and others) that tell Docker how to assemble an image. None of them are control flow statements, so conditional logic comes from Unix shell constructs inside RUN, evaluating variables passed as build arguments or environment variables.
Dockerfile with an if/else on BUILD_ENV
Here the behavior depends on an external argument BUILD_ENV, which is either development or production.
- Arguments and environment variables:
ARGdefinesBUILD_ENV, andENVsetsAPP_HOME. - Shell conditional: the
RUNinstruction checksBUILD_ENV. If it is'production', it installsnginx. Otherwise it installsnginxpluscurl, so theCMDstill hasnginxto start. - Execution: pass
BUILD_ENVwith--build-argwhen you build:
Ways to pass the external argument
External arguments let you change build behavior without editing the Dockerfile:
--build-arg: as shown above, sets build-time variables.- Default values: an
ARGcan be given a default value in the Dockerfile and overridden at build time. - Docker Compose: define build arguments in
docker-compose.yml:
| Feature | Usage |
Argument (ARG) | Declare build-time variables inside Dockerfile.
Used with --build-arg during docker build. |
Environment (ENV) | Set environment variables accessible during build and run time. |
| Conditionals | Achieved using shell scripting inside RUN commands. |
| Use Case | Modify INSTALL step based on environment for lighter production images. |
Related reading
- Dockerfile Is there any way to read variables from .env file
- Dockerfile strategies for Git
- Docker/Kubernetes Gunicorn/Celery - Multiple Workers vs Replicas?
- docker.sock permission denied
- Does Alpine have known DNS issue within Kubernetes?
- Does Kubernetes cache docker-registry secrets?
- Does kubernetes have its own Load Balancer?
- domain configuration in docker-compose
System design interview problems on this topic
- Design a Container Orchestration System: solution and walkthrough
- Design a Code Deployment System: solution and walkthrough
- Design GitHub Actions: solution and walkthrough
- Design a Serverless Architecture Framework: solution and walkthrough

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseSystem Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.