Search code examples
dockerdockerfiledocker-build

Conditional logic in Dockerfile, using --build-arg


Say I have this:

ARG my_user="root"  # my_user => default is "root"
USER $my_user
ENV USER=$my_user

All good so far, but now we get here:

ENV HOME="/root"

is there a way to do something like this:

ENV HOME $my_user === "root"? "/root" : "/home/$my_user"

Obviously, that's the wrong syntax.

The only solution I can think of is to just use two --build-args, something like this:

docker build -t zoom \
    --build-arg my_user="foo"  \
    --build-arg my_home="/home/foo"  \
     .

Solution

  • Unfortunately you can't do this directly

    https://forums.docker.com/t/how-do-i-send-runs-output-to-env-in-dockerfile/16106/3

    So you have two alternatives

    Use a shell script at start

    You can use a shell script at the start

    CMD /start.sh
    

    And in your start.sh you can have that logic

    if [ $X == "Y" ]; then
       export X=Y
    else
       export X=Z
    fi
    

    Create a profile environment variable

    FROM alpine
    
    RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh
    SHELL ["/bin/sh", "-lc"]
    CMD env
    

    And then you when you run it

    $ docker run test
    HOSTNAME=d98d44fa1dc9
    SHLVL=1
    HOME=/root
    PAGER=less
    PS1=\h:\w\$
    NAME=TARUN
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    PWD=/
    CHARSET=UTF-8
    

    Note: The SHELL ["/bin/sh", "-lc"] is quite important here, else the profile will not be loaded

    Note2: Instead of RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh you can also do a COPY myevn.sh /etc/profile.d/myenv.sh and have the file be present in your build context