skip to Main Content

I cannot get conditional Dockerfile to work.

My command is: docker build -t test --progress=plain --build-arg APP_BRANCH=main.

FROM alpine:latest AS base

ARG APP_BRANCH

I’ve tried using simple if…else:

RUN

    if [ "${APP_BRANCH}" == "main" ];

        then echo "MAIN app";

    elif [ "${APP_BRANCH}" == "dev" ];

        then echo "DEV app";

    else echo "Something else!!";

    fi

and I receive something like /bin/sh: 1: [: main: unexpected operator fixed

just to see if variable is set. And it is.

Then I tried to use MultiStage build:

FROM base AS main

RUN echo "MAIN"



FROM base AS prod

RUN echo "PROD"



FROM ${APP_BRANCH} AS final

RUN echo "FINAL"

and got output: base name (${APP_BRANCH}) should not be blank

I also did try to use ${APP_BRANCH} var in entrypoint

ENTRYPOINT ["java", "-jar", "/usr/share/myapp/myAppName-${APP_BRANCH}.jar

but it behaves like the variable is not set. Buildkit is disabled. What can I do to make it work?

3

Answers


  1. Chosen as BEST ANSWER

    The main issue in this case was ENTRYPOINT. As it is described here: https://emmer.dev/blog/docker-shell-vs.-exec-form/ and here: https://engineering.pipefy.com/2021/07/30/1-docker-bits-shell-vs-exec/ ENTRYPOINT is a little bit tricky. It takes two forms: exec or shell. Exec form does not substitute variables. Shell form does substitute ENV variables and is more suitable for this case. Example code could be like follows:

    ARG APP_BRANCH
    ENV APP_BRANCH=${APP_BRANCH}
    ENTRYPOINT java -jar /usr/share/myapp/myAppName-$APP_BRANCH.jar
    

    Please note how APP_BRACH var is registered in the first line, assigned to ENV var of the same name in second line, and then used in shell type entrypoint. Also note differencies between ENTRYPOINT described earlier (exec type) and shell type written above. Shell command is not surrounded with sqare brackets and quotation marks.


  2. I can’t reproduce your issue.

    With the following Dockerfile

    FROM alpine:latest
    ARG APP_BRANCH
    RUN
        if [ "${APP_BRANCH}" == "main" ];
            then echo "MAIN app";
        elif [ "${APP_BRANCH}" == "dev" ];
            then echo "DEV app";
        else echo "Something else!!";
        fi
    

    and this build command

    docker build --no-cache --build-arg APP_BRANCH=main . --progress=plain
    

    it builds successfully and shows MAIN app in the build output.

    This is on an Ubuntu 20.04 host and Docker 23.0.1.

    If you still have the issue, please edit your post to include a full Dockerfile and the exact command you use to build it.

    Login or Signup to reply.
  3. The error message looks like from dash. == is nonstandard argument to [. = is standard. Use [ "${APP_BRANCH}" = "main" ].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search