Middle
Middle

Reputation: 367

Docker Conditional build image

I have to execute the same script to two docker images.

My Dockerfile are:

FROM centos:6
...

and

FROM centos:7
...

Is it possibile to have a single file and pass a parameter, something like:

FROM centos:MYPARAMS

and during the build somethings like that:

docker build --no-cache MYPARAMS=6  .

Thank you

Upvotes: 12

Views: 8082

Answers (3)

Jan Oudrnicky
Jan Oudrnicky

Reputation: 511

Just to put this in right context, it is now (since May 2017) possible to achieve this with pure docker since 17.05 (https://github.com/moby/moby/pull/31352)

Dockerfile should look like (yes, commands in this order):

ARG APP_VERSION
ARG GIT_VERSION
FROM app:$APP_VERSION-$GIT_VERSION

Then build is invoked with

docker build --build-arg APP_VERSION=1 --build-arg GIT_VERSION=c351dae2 .

Docker will try to base the build on image app:1-c351dae2

Helped me immensely to reduce logic around building images.

Upvotes: 32

Wolfgang Fahl
Wolfgang Fahl

Reputation: 15776

At https://github.com/BITPlan/docker-stackoverflowanswers/tree/master/33351864 you'll find a bash script "build" that works the way you want.

wf@mars:~/source/docker/docker-stackoverflowanswers/33351864>./build -v 6
Sending build context to Docker daemon 3.584 kB
Step 0 : FROM centos:6
6: Pulling from library/centos
fa5be2806d4c: Pull complete 
ebdbe10e9b33: Downloading 4.854 MB/66.39 MB
...

wf@mars:~/source/docker/docker-stackoverflowanswers/33351864>./build -v 7
Sending build context to Docker daemon 3.584 kB
Step 0 : FROM centos:7

The essential part is the "here" document used:

#
# parameterized dockerfile
#
dockerfile() {
  local l_version="$1"
cat << EOF > Dockerfile
FROM centos:$l_version
EOF
}

Upvotes: 2

Maxime
Maxime

Reputation: 10618

From my knowledge, this is not possible with Docker.

The alternative solution is to use a Dockerfile "template", and then parse it using the template library of your choice. (Or even using sed command)

Upvotes: 4

Related Questions