Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create flexible onbuild docker image that uses env vars?

I have a base onbuild tagged docker image that I would like to use as a template for builds but I want the child image to be able to set an ENV var to modify the ONBUILD instructions

base-onbuild:

FROM root-image

RUN mkdir -p /app/src
UNBUILD COPY . /app/src/
ONBUILD WORKDIR /app/src
ONBUILD RUN ./build ${TARGET_APP}
ONBUILD RUN cp ${TARGET_APP}/build/bin /app/bin

my-app:

FROM base-onbuild

ENV TARGET_APP my-app
CMD my-app

According to the docker documentation the ONBUILD steps get run immediately after the FROM base-onbuild clause, so before the ENV statement that sets TARGET_APP so in the ONBUILD steps TARGET_APP is not set.

I have also tried to pass the TARGET_APP value via the --build-args argument of docker build but this also didn't have any effect.

Is there another way that I can set variables and modify the UNBUILD steps?

similar question: Placeholder field for the ONBUILD section for child docker images to use

like image 694
craigb Avatar asked Oct 19 '22 21:10

craigb


1 Answers

Mandatory arg

I have something that works for the case in your question, but it won't work for all cases in general.

In your dockerfile after ONBUILD WORKDIR /app/src, you'll have:

COPY build_copy.sh /config
ONBUILD COPY target_app.txt /config
ONBUILD RUN sh /config/build_copy.sh

The file build_copy.sh will contain the following lines:

TARGET_APP=`cat /config/target_app.txt`
ONBUILD RUN ./build $TARGET_APP
ONBUILD RUN cp $TARGET_APP/build/bin /app/bin

The file target_app.txt should contain the text you wanted to put into TARGET_APP. This will require you to have a file target_app.txt in your child image.


Optional arg

You can somewhat mitigate this by using putting 'optional' text files in a folder /config in your child root and changing your ONBUILD to:

ONBUILD COPY /config /config

You'll only need the folder then, all files in there would be optional. The shell script can then use:

TARGET_APP_2=`cat /config/target_app.txt`
if [ -n "$TARGET_APP_2" ]
then
  TARGET_APP=$TARGET_APP_2
else
  TARGET_APP='default_app'
fi
like image 103
HSquirrel Avatar answered Nov 02 '22 18:11

HSquirrel