A Dockerfile has no IF or ELSE instruction. There is no way to write “if this build argument is set, run this step, otherwise run that one” as a Dockerfile keyword. You still have several reliable ways to get conditional builds, and each one fits a different job:
- Shell
if/elseinsideRUN: the quickest way to run different commands based on a build argument. - A
casestatement in a heredocRUN: easier to read when there are more than two choices. - Multi-stage builds with
ARGinFROM: choose a whole stage. This is the cleanest option, and BuildKit skips the stages you don’t use. - Variable defaults in
ENV: set a value only when an argument is given, or fall back to a default.
This guide covers each method with a working example. All examples were tested with Docker Engine 29 and BuildKit, which is the default builder since Docker Engine 23.0. If you don’t have Docker yet, see how to install Docker on Ubuntu 26.04.
ARG vs ENV: Which Variables Can You Test?
Conditions in a Dockerfile almost always test a variable, so you need to know the two kinds:
ARGdefines a build-time variable. You set it withdocker build --build-arg NAME=value. It exists only while the image is being built and isn’t available in a running container.ENVsets an environment variable that is stored in the image. It is available to later build steps and to every container started from the image.
Use ARG for decisions you make at build time, such as which package, environment or feature to include. Always give it a default value (ARG WEBSERVER=nginx) so the build still works when nobody passes --build-arg. For more on runtime variables, read setting up environment variables in Docker.
1. If-Else in a RUN Instruction
RUN runs its command in a shell (/bin/sh -c on Linux images), so you can use a normal shell if/elif/else block. This example installs either Nginx or Apache, depending on a build argument:
Dockerfile:
FROM ubuntu:24.04
# Build argument with a safe default
ARG WEBSERVER=nginx
RUN apt-get update && \
if [ "$WEBSERVER" = "nginx" ]; then \
apt-get install -y --no-install-recommends nginx; \
elif [ "$WEBSERVER" = "apache" ]; then \
apt-get install -y --no-install-recommends apache2; \
else \
echo "Unsupported WEBSERVER: $WEBSERVER" >&2; \
exit 1; \
fi && \
rm -rf /var/lib/apt/lists/*
Build it with the default value (Nginx):
docker build -t myweb:nginx .
Or choose Apache with --build-arg:
docker build --build-arg WEBSERVER=apache -t myweb:apache .
A few details matter here:
- Every line except the last ends with
\, and every shell command inside the block ends with;. Docker joins the lines into one shell command, so a missing;beforefiorelsecauses a syntax error. - Quote the variable (
"$WEBSERVER"). An empty or unset argument then gives a clean comparison instead of a shell error. - Use
=, not==. Ubuntu and Debian images runRUNwithdash, which only supports the POSIX=inside[ ]. - Fail on bad input. The
elsebranch callsexit 1, so a typo such asWEBSERVER=apachstops the build with an error instead of quietly producing an image with no web server.
2. Multiple Choices with case and a Heredoc
Long if chains full of backslashes are hard to read. With the Dockerfile 1.4+ syntax (standard with BuildKit), you can write a multi-line script as a heredoc, without any \ or ; at line ends. A case statement then handles several values neatly:
Dockerfile:
# syntax=docker/dockerfile:1
FROM alpine:3.22
ARG APP_ENV=production
RUN <<EOT
set -e
case "$APP_ENV" in
production)
echo "Optimised build" > /build-info
;;
development|dev)
apk add --no-cache curl
echo "Debug build" > /build-info
;;
*)
echo "Unknown APP_ENV: $APP_ENV" >&2
exit 1
;;
esac
EOT
docker build --build-arg APP_ENV=dev -t myapp:dev .
The development|dev pattern accepts either value, and *) catches everything else. Keep set -e at the top so the build stops if any command in the script fails.
3. Choose a Build Stage with ARG in FROM (Recommended)
If the two branches differ a lot (different packages, files or configuration), don’t put everything in one big RUN. Write each branch as its own stage and let a build argument pick the stage. This is the closest thing to a real if-else in a Dockerfile:
Dockerfile:
# Global ARG: must come before the first FROM to be usable in FROM lines
ARG BUILD_ENV=prod
FROM alpine:3.22 AS base
WORKDIR /app
# "if" branch
FROM base AS build-dev
RUN echo "debug=true" > config.ini
# "else" branch
FROM base AS build-prod
RUN echo "debug=false" > config.ini
# Pick the branch from the build argument
FROM build-${BUILD_ENV} AS final
CMD ["cat", "/app/config.ini"]
Build the default (prod) image, then the dev one:
docker build -t myapp:prod .docker build --build-arg BUILD_ENV=dev -t myapp:dev .
Run them to check the result:
docker run --rm myapp:proddebug=falsedocker run --rm myapp:devdebug=true
Why this pattern works well:
- BuildKit skips unused stages. When you build
prod, thebuild-devstage never runs. You can see this in the build output, where only[build-prod]steps appear. - Each branch has its own layers and cache, so switching between them doesn’t invalidate the other branch.
- Conditional COPY becomes easy: put a different
COPYin each stage, for example a debug config inbuild-devand a production config inbuild-prod.
Two rules to remember: an ARG declared before the first FROM can only be used in FROM lines. To use it inside a stage, declare it again there with ARG BUILD_ENV (no value needed). Also always give it a default. If BUILD_ENV is empty, the base image becomes build- and the build fails with invalid reference format. docker build --check . reports this mistake as an InvalidDefaultArgInFrom warning before you build.
You can also build a stage directly with --target, for example docker build --target build-dev -t myapp:dev .. That works well in CI, but the ARG in FROM approach keeps a sensible default when someone runs a plain docker build. See this multi-stage Dockerfile example for a larger real-world build.
4. Conditional Values with Variable Defaults
Sometimes you only need a value, not a different command. Dockerfile ENV, ARG, WORKDIR, COPY and other instructions support two shell-style modifiers:
${VAR:-word}: useVARif it is set, otherwise useword.${VAR:+word}: usewordifVARis set, otherwise an empty string.
Dockerfile:
FROM alpine:3.22
ARG VERSION
ARG DEBUG
# "latest" unless VERSION is passed
ENV APP_VERSION=${VERSION:-latest}
# "debug" only if DEBUG is passed (any value), otherwise empty
ENV LOG_LEVEL=${DEBUG:+debug}
CMD ["sh", "-c", "echo version=$APP_VERSION log_level=${LOG_LEVEL:-info}"]
docker build -t myapp . && docker run --rm myappversion=latest log_level=infodocker build --build-arg VERSION=2.1 --build-arg DEBUG=1 -t myapp . && docker run --rm myappversion=2.1 log_level=debug
Note that ${DEBUG:+debug} only checks whether DEBUG has a value. DEBUG=0 or DEBUG=false also count as “set”. To test for a specific value, use a RUN condition (method 1) instead.
5. Conditions Based on the Target Platform
When you build multi-platform images with docker buildx build --platform linux/amd64,linux/arm64, BuildKit sets automatic build arguments such as TARGETARCH (amd64, arm64…) and TARGETOS. Declare the argument inside the stage before you use it:
FROM alpine:3.22
ARG TARGETARCH
RUN if [ "$TARGETARCH" = "arm64" ]; then \
echo "Downloading the ARM64 binary"; \
else \
echo "Downloading the $TARGETARCH binary"; \
fi
This is the usual way to download the right release binary for each CPU architecture. Without the ARG TARGETARCH line, the variable is empty inside RUN.
6. Copy a File Only If It Exists
A common question is how to make COPY optional. With BuildKit, a wildcard pattern that matches nothing is not an error, so you can wrap the last character of an optional file in brackets:
# app.txt is required; config.json is copied only if it exists
COPY app.txt config.jso[n] /app/
Keep at least one file that always exists in the same COPY line, and remember this depends on the build context, not on a build argument. To copy different files based on an argument, use separate stages (method 3). The differences between the two copy instructions are covered in ADD vs COPY in Dockerfile.
Passing Build Arguments from Docker Compose
If you build with Docker Compose, set the same arguments under build.args:
services:
web:
build:
context: .
args:
WEBSERVER: apache
BUILD_ENV: dev
Then run docker compose build. Compose passes each value as a --build-arg.
Which Method Should You Use?
| Need | Best method |
|---|---|
| Run one of two commands | Shell if/else in RUN |
| Three or more options | case in a heredoc RUN |
| Different packages, files or config per environment | Multi-stage build with ARG in FROM |
| Set a value or fall back to a default | ${VAR:-default} / ${VAR:+value} |
| Different steps per CPU architecture | TARGETARCH in a RUN condition |
| Optional file in the build context | Wildcard COPY (file.jso[n]) |
Best Practices
- Give every
ARGa default so a plaindocker build .always produces a working image. - Fail fast on invalid values with
exit 1instead of building a half-configured image. - Keep conditions in as few
RUNsteps as possible. EachRUNadds a layer, and cleanup such asrm -rf /var/lib/apt/lists/*only shrinks the image when it runs in the same step as the install. - Prefer stages over long shell scripts. When a
RUNblock grows beyond a few branches, move each branch into its own stage. - Remember build arguments affect the cache. Every
RUNafter anARGsees it as an environment variable, so changing its value invalidates the cache from the firstRUNafter theARG. Declare arguments as late as possible, just before the step that needs them. - Never pass secrets with
--build-arg. Argument values stay visible in the image history. Rundocker history --no-truncon an image and you’ll see lines likeRUN |1 WEBSERVER=apache .... UseRUN --mount=type=secretfor secrets instead. - Lint before you build:
docker build --check .runs Docker’s build checks without building the image.
For more ways to keep images small and secure, see how to optimize a Dockerfile for production.
FAQ
Does Dockerfile support if-else statements?
No. The Dockerfile format has no IF, ELSE or loop instruction. You get conditional behaviour from shell logic inside RUN, from choosing a stage with an ARG in FROM, or from ${VAR:-default} variable expansion.
How do I run a RUN step only if a build argument is set?
Test the argument in the shell: RUN if [ -n "$MY_ARG" ]; then your-command; fi. -n is true when the variable is not empty. Use -z for the opposite check.
Can I use an ARG inside an if condition after FROM?
Yes, but you must declare the ARG inside the stage (after FROM). An ARG declared before the first FROM is only available to FROM lines unless you repeat ARG NAME in the stage.
Why does my if statement give “syntax error: unexpected end of file”?
Usually a missing ; before then, else or fi, or a missing \ at the end of a line. Docker joins the lines into a single shell command, so each statement needs a ; separator. Switching to a heredoc RUN <<EOT avoids both problems.
How do I conditionally copy files in a Dockerfile?
There is no conditional COPY. Either use a wildcard pattern such as COPY config.jso[n] /app/, which copies nothing when the file is missing, or put a different COPY in each build stage and choose the stage with a build argument.
Conclusion
Dockerfiles don’t have a built-in if-else, but they don’t need one. Use a shell if or case in RUN for small decisions, and use multi-stage builds with ARG in FROM when the branches differ a lot. With defaults on every argument and an exit 1 for invalid values, your conditional builds stay predictable. To learn more about the build command itself, read our docker build guide.
How did it make you feel?
