0
0
DockerHow-ToBeginner · 3 min read

How to Use Conditional Statements in Dockerfile

Dockerfile does not support direct if statements, but you can use ARG to pass build-time variables and combine them with shell if commands inside RUN instructions to create conditionals. This lets you customize image builds based on arguments.
📐

Syntax

Dockerfile uses ARG to define build-time variables and RUN to execute shell commands where you can write conditionals using shell syntax.

Key parts:

  • ARG name[=default]: Defines a build argument.
  • RUN: Runs shell commands where you can use if statements.
  • Use $name to access argument values inside commands.
dockerfile
ARG FEATURE_ENABLED=false
RUN if [ "$FEATURE_ENABLED" = "true" ]; then \
    echo "Feature is enabled"; \
else \
    echo "Feature is disabled"; \
fi
💻

Example

This example shows how to enable or disable a feature during build using an argument and a conditional shell command inside RUN.

dockerfile
FROM alpine:3.18

ARG FEATURE_ENABLED=false

RUN if [ "$FEATURE_ENABLED" = "true" ]; then \
    echo "Feature is enabled" > /feature.txt; \
else \
    echo "Feature is disabled" > /feature.txt; \
fi

CMD cat /feature.txt
Output
Feature is enabled
⚠️

Common Pitfalls

Common mistakes when using conditionals in Dockerfile include:

  • Trying to use if directly in Dockerfile instructions (not supported).
  • Not quoting variables in shell commands, which can cause syntax errors.
  • Forgetting to escape line breaks with \ in multi-line RUN commands.
  • Not passing build arguments with --build-arg during docker build.
dockerfile
### Wrong way (will fail):
# if [ "$FEATURE_ENABLED" = "true" ]; then echo "yes"; fi

### Right way:
ARG FEATURE_ENABLED=false
RUN if [ "$FEATURE_ENABLED" = "true" ]; then echo "yes"; fi
📊

Quick Reference

CommandDescription
ARG name[=default]Define a build-time variable
RUN Run shell commands where conditionals can be used
$VARIABLEAccess argument or environment variable in shell
docker build --build-arg name=valuePass argument value during build
\Escape line breaks in multi-line RUN commands

Key Takeaways

Dockerfile does not support direct if statements but allows conditionals inside RUN shell commands.
Use ARG to define build-time variables and pass values with --build-arg during docker build.
Always quote variables and escape line breaks in multi-line RUN commands to avoid errors.
Conditionals in Dockerfile rely on shell scripting inside RUN instructions.
Test your Dockerfile builds with different ARG values to verify conditional behavior.