- Published on
Docker Build Context and the Path You Run the Build From
- Authors
- Name
- Yair Mark
- @yairmark
On the project I am currently working on I broke the app's dockerfile into multiple parts: for the parent file and for each component making up the app. This resulted in there being multiple files in the root of the project which made it a bit messy.
In an attempt to resolve this issue I created an infrastructure
folder in the root of the project to house these files. I moved the docker files and its dependencies there and updated the inside of the dockerfiles so that they refer to project files one directory up when doing a COPY
or an ADD
. This resulted in the error: COPY failed: Forbidden path outside the build context
.
A dockerfile can be located in a location other than the root of the project and can be referred to using -f ./path/to/Dockerfile
but the files that the dockerfile can access using COPY
and ADD
are restricted to the docker build context.
The docker build
command expects some sort of PATH
. This path is the build context i.e. the folders that the Dockerfile has access to. You need to write your ADD
s and COPY
s in the dockerfile in relation to the build path and not the dockerfile's location.
For example I have the following structure:
root
-> infrastructure
-> Dockerfile
-> dockerdependencies
-> .bashrc
-> makefile
The makefile
has a docker build command and is run from the root of the project. It has a target that looks like this:
docker build -t container-tag-name . -f ./infrastructure/Dockerfile
In the above command the .
after the tagname is the build context which is the root of the project as that is where the makefile
is run from.
In the Dockerfile we add the .bashrc
file as:
COPY ./infrastructure/dockerdependencies/.bashrc /root/home
As the context of this docker build
command is the root of the project I have to refer to ./infrastructure/dockerdependencies
in relation to that as the project root is the docker build context.
A more detailed explanation of this can be found here.