{

Conditional if else in docker with examples


This tutorial explains How to write if-else conditional statements in Docker

Docker if else conditional arguments

Declared a variable environment

There are no IF else conditionals in the Docker file. You have to write a shell script syntax for if else condition

Use the RUN command with bash or Shell script to execute in a single line.

Here is a syntax file

You can write the RUN command in a single line or multiple lines

RUN if [ condition1 ]; then command1; else command2;  fi

Multiple lines by appending \

RUN if [ condition1 -o condition2 ]; then \
      command1; \
    else \
      command2; \
    fi

Here is an example

ARG environment
RUN if [ "$environment" = "production" ] ; then npm run build ; else npm run dev ; fi

In the same way we can write in multi-line commands by appending \

ARG environment
RUN if [ "$environment" = "production" ] ; then \
        npm run build ;\
    else 
        npm run dev; \
    fi\

Pass the environment variable to the docker file using the --build-arg command Run the below command

docker build -t myimage . --build-arg environment=production
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.