Raynor Kuang
Raynor Kuang

Reputation: 491

Conditionally setting ENV vars in Dockerfile based on build ARG

I'd like to conditionally set some ENV vars in my Dockerfile based on certain build ARGs. For one reason or another, the ENV var doesn't map directly to the actual build ARG i.e. I can NOT do the following:

ARG myvar
ENV MYVAR $MYVAR

It's complex enough a mapping that I can't just do, like, "prefix-${$MYVAR}", or whatever, either.

I'm aware of just using a shell command with EXPORT instead (and then having access to if statements), but exporting the environmental variable this way won't persist across containers the way I need to. If the only solution is to just repeatedly prefix the needed env for every RUN/CMD I need it for (and all the logic needed to get there), then I would accept that.

I'm also aware of this answer Conditional ENV in Dockerfile, which does have one solution where a (essentially) ternary is used to trigger a certain ENV value, but because my situation is more complex, I can't just use that given solution.

Is there a way to write "logic" inside Dockerfiles, while still having access to Docker commands like ENV?

Any help would be really appreciated!

PS.

This is a Dockerfile to build a Node image, so my last few steps look basically like

RUN npm run build
CMD ["npm", "run", "start"]

Upvotes: 4

Views: 1023

Answers (2)

Siegfried
Siegfried

Reputation: 90

I had a similar issue for setting proxy server on a container.

The solution I'm using is an entrypoint script, and another script for environment variables configuration. Using RUN, you assure the the configuration script runs on build, and ENTRYPOINT when you run the container.

The entrypoint script looks like:

#!/bin/bash
    
# Run any other commands needed 

# Run the main container command
exec "$@"

And in the Dockerfile, configure:

#copy bash scripts
COPY configproxy.sh /root
COPY startup.sh .    
RUN ["/bin/bash", "-c", ". /root/configproxy.sh"]
ENTRYPOINT ["./entrypoint.sh"]
CMD ["sh", "-c", "bash"]

Take a look here.

Upvotes: 0

Siyu
Siyu

Reputation: 12079

If I understand your question correctly, you want

if BUILD_VAR == v1:
  set ENV MYVAR=aValue
else if YOUR_VAR == v2:
  set ENV MYVAR=anotherValue

Solution:

ARG BUILD_VAR=v1

FROM scratch as build_v1
ONBUILD ENV MYVAR=aValue

FROM scratch as build_v2
ONBUILD ENV MYVAR=anotherValue

FROM build_${YOUR_VAR} AS final
...
RUN npm run build
CMD ["npm", "run", "start"]

The toplevel BUILD_VAR allows you to pass the condition with docker build --build-arg BUILD_VAR=v1 .

ONBUILD is used so the instruction ENV is only executed if the corresponding branch is selected.

Upvotes: 2

Related Questions