Alexander Mills
Alexander Mills

Reputation: 100040

How can we use shared Dockerfile's which reside in different directories than the "current build context path"?

With the following filesystem structure in mind:


enter image description here

I want to execute docker build and copy the “default.sh” file to the Docker container. I want to use DockerfileB for directories a, b and c. And apply the same Dockerfile to all 3 of those scripts. However, Docker throws an error saying the Dockerfile must be in the same build context.

So I run this:

cd /home/oleg/WebstormProjects/oresoftware/sumanjs/suman/test/groups/c &&  docker build --file=/home/oleg/WebstormProjects/oresoftware/sumanjs/suman/test/groups/Dockerfile -t c . 

and I get this error:

unable to prepare context: The Dockerfile (/home/oleg/WebstormProjects/oresoftware/sumanjs/suman/test/groups/DockerfileB) must be within the build context (.)

Is there any way around this? Maybe symlinks? Desperate for a solution to this, because I would like to share Dockerfiles instead of having to copy identical ones to subfolders, etc.

Upvotes: 0

Views: 95

Answers (1)

Matt
Matt

Reputation: 74710

Symlinks won't work in this case for the same reason as the Dockerfile, the symlink target will be outside the "build context" and Docker doesn't allow that.

Hard linking the Dockerfile in each a, b and c directories would work to share the one file for Docker, but that doesn't work nicely with source control, like Git.

A build argument might allow reuse of the Dockerfile. Use a docker build context of the groups directory and whenever you need to reference one of the directories in the Dockerfile, use the variable/argument.

FROM alpine
ARG DIR
COPY ${DIR}/default.sh /default.sh

Then run with

cd groups
docker run --build-arg DIR=c -f ./DockerfileB .

Upvotes: 1

Related Questions