Pradeepb
Pradeepb

Reputation: 2562

Is there a way to use If condition in Dockefile?

I am new to docker, I am looking for a way to execute a command in docker container depends on the environment.

In Dockerfile, I have 2 commands, command_a and command_b. If the env = 'prod' run command_a, else command_b. How can I achieve this?

I tried like below:

RUN if [ $env = "prod" ] ; then echo command_a; else echo cpmmand_b; fi;

How can I achieve the desired behaviour?

PS: I know that echo should not be there.

Upvotes: 5

Views: 6287

Answers (1)

Mattias Wadman
Mattias Wadman

Reputation: 11425

Docker 17.05 and later supports a kind of conditionals using multi-stage build and build args. Have a look at https://medium.com/@tonistiigi/advanced-multi-stage-build-patterns-6f741b852fae

From the blog post:

ARG BUILD_VERSION=1
FROM alpine AS base
RUN ...
FROM base AS branch-version-1
RUN touch version1
FROM base AS branch-version-2
RUN touch version2
FROM branch-version-${BUILD_VERSION} AS after-condition
FROM after-condition 
RUN ...

And then use docker build --build-arg BUILD_VERSION=value ...

Upvotes: 3

Related Questions