Skip to content

Using If-Else in Dockerfile: Conditional Builds with ARG, RUN and Multi-Stage

Dockerfile has no IF instruction. Learn 6 tested ways to add if-else logic: shell conditions in RUN, case heredocs, ARG in FROM to pick a stage, ENV defaults and TARGETARCH.

Covers
Docker
Versions & support
About Docker →
On this page

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/else inside RUN: the quickest way to run different commands based on a build argument.
  • A case statement in a heredoc RUN: easier to read when there are more than two choices.
  • Multi-stage builds with ARG in FROM: 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:

  • ARG defines a build-time variable. You set it with docker build --build-arg NAME=value. It exists only while the image is being built and isn’t available in a running container.
  • ENV sets 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 ; before fi or else causes 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 run RUN with dash, which only supports the POSIX = inside [ ].
  • Fail on bad input. The else branch calls exit 1, so a typo such as WEBSERVER=apach stops 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.

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:prod
debug=false
docker run --rm myapp:dev
debug=true

Why this pattern works well:

  • BuildKit skips unused stages. When you build prod, the build-dev stage 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 COPY in each stage, for example a debug config in build-dev and a production config in build-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}: use VAR if it is set, otherwise use word.
  • ${VAR:+word}: use word if VAR is 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 myapp
version=latest log_level=info
docker build --build-arg VERSION=2.1 --build-arg DEBUG=1 -t myapp . && docker run --rm myapp
version=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?

NeedBest method
Run one of two commandsShell if/else in RUN
Three or more optionscase in a heredoc RUN
Different packages, files or config per environmentMulti-stage build with ARG in FROM
Set a value or fall back to a default${VAR:-default} / ${VAR:+value}
Different steps per CPU architectureTARGETARCH in a RUN condition
Optional file in the build contextWildcard COPY (file.jso[n])

Best Practices

  • Give every ARG a default so a plain docker build . always produces a working image.
  • Fail fast on invalid values with exit 1 instead of building a half-configured image.
  • Keep conditions in as few RUN steps as possible. Each RUN adds a layer, and cleanup such as rm -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 RUN block grows beyond a few branches, move each branch into its own stage.
  • Remember build arguments affect the cache. Every RUN after an ARG sees it as an environment variable, so changing its value invalidates the cache from the first RUN after the ARG. 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. Run docker history --no-trunc on an image and you’ll see lines like RUN |1 WEBSERVER=apache .... Use RUN --mount=type=secret for 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.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top