Dockerfile if else condition with external arguments
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Explanation
- Arguments and Environment Variables: The Dockerfile uses
ARGto defineBUILD_ENV. This is converted into an environment variable usingENV. - Shell Command for Conditional: The
RUNinstruction contains a shell script that checks the value ofBUILD_ENV. If it's'production', it installsnginx. Otherwise, it installscurl. - Execution: When building the image, you specify the
BUILD_ENVwith the--build-argoption in thedocker buildcommand.
Using External Arguments
External arguments offer significant flexibility, allowing you to adjust build behavior without changing the Dockerfile.
How to Pass External Arguments
External arguments can be passed in various ways:
- Using
--build-arg: As shown in the example above. This allows you to specify build-time variables. - Environment Variables (
-e): Docker'sARGin a Dockerfile can be given default values and be overridden via this option. - Docker Compose: You can define build arguments in your
docker-compose.yml.
Example entry in docker-compose.yml:
Key Points Table
| 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. |
Conclusion
While Dockerfiles don't natively support control flow like if-else, you can effectively use shell scripting to implement conditional logic. With this approach, you can create dynamic and adaptable Docker builds that cater to various environments and configurations. By carefully leveraging arguments and environment variables, developers can fine-tune their Docker images, resulting in optimized, environment-specific deployments.
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 Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.