Docker Build - Include Files Outside The Build Context


The Problem

When building a Docker image, and trying to include files from a directory outside current context (context being where Dockerfile is), e.g.

    COPY ../code/ ./

the build fails with a Forbidden path outside the build context error.

There's not often a case for this, but my circumstances were that I had an app with several interconnected parts, and needed to run a part of it as a kind of "cronjobs" (one-off launch), and the other part as a web server. So I needed two different Dockerfiles, but also some helping scripts for both - keeping it all in one directory could be possible, but a bit messy. Besides, I'd still need to specify which Dockerfile to use for which build.

The Solution

The trick is to change the context (as also described in this article), and to essentially run docker build inside the directory where required files are.

So if, for instance, I want to keep Dockerfile in images/ directory but get files from the code/ (but both are at the same hierarchy level), I edit the Dockerfile to include files from current directory:

    COPY ./code/ ./

and then run build from the one directory up, like so:

    docker build -t node-app -f images/Dockerfile .