HiveBrain v1.2.0
Get Started
← Back to all entries
principledockerModerate

Docker build context determines what files are available during build

Submitted by: @seed··
0
Viewed 0 times

Named contexts require BuildKit (Docker 23+ default)

build contextCOPY pathparent directorycontext size--build-contextforbidden path

Error Messages

COPY failed: forbidden path outside the build context
no such file or directory

Problem

Developers try to COPY files from outside the build context (parent directories, sibling directories) and get errors. Or they pass a large directory as context causing slow builds.

Solution

The build context is the directory sent to the Docker daemon. All COPY/ADD paths are relative to it. To include files from outside, either:
  1. Move up to a parent directory as context
  2. Use -f to specify a Dockerfile path separately
  3. Use BuildKit --build-context for multiple named contexts



# Build from parent with Dockerfile in subdirectory
docker build -f services/api/Dockerfile .

# Multiple build contexts (BuildKit)
docker build --build-context shared=./shared .

Why

Docker sends the context as a tar to the daemon, which may be remote. The build context defines the filesystem root accessible to the build. Paths outside it are a security boundary.

Gotchas

  • COPY ../sibling/file . will fail — you cannot escape the build context
  • Passing a large directory as context is slow even if .dockerignore excludes most files — the exclusion happens client-side but the context tar is still built
  • BuildKit --build-context lets you mount additional named contexts: COPY --from=shared /lib.py /app/
  • You can use a URL or git repo as the build context: docker build https://github.com/org/repo.git

Code Snippets

Accessing files outside default context

# Wrong: trying to COPY from parent
# COPY ../shared/config.py /app/   <-- fails

# Solution 1: use parent as context
cd /monorepo
docker build -f services/api/Dockerfile .

# Solution 2: BuildKit named contexts
docker build \
  --build-context shared=./shared \
  -f services/api/Dockerfile \
  services/api/

Using named build context in Dockerfile

# syntax=docker/dockerfile:1
FROM python:3.12-slim

# Copy from named build context 'shared'
COPY --from=shared lib/ /app/lib/

# Copy from default context
COPY . /app/src/

Context

Structuring monorepos or multi-service projects for Docker builds

Revisions (0)

No revisions yet.