DevOpsil
DockerMedium

Fix: Docker Build Context or Layer Failure

docker build fails with 'COPY failed: file not found in build context'

!Symptoms

  • docker build fails with 'COPY failed: file not found in build context'
  • Build is extremely slow due to large context size
  • Layer caching is not working, every build reinstalls dependencies
  • Multi-stage build fails with 'failed to compute cache key'

?Root Causes

  • File referenced in COPY/ADD is not in the build context directory
  • .dockerignore is missing, sending GBs of unnecessary files as context
  • Incorrect COPY instruction order breaking layer cache
  • Referring to a file from a different build stage incorrectly
  • Build context is a symlink or outside the expected directory

#Diagnosis Steps

  1. 1Check build context size: look at 'Sending build context to Docker daemon' line
  2. 2Verify the file exists in the build context: `ls -la <file>` relative to Dockerfile location
  3. 3Review .dockerignore: `cat .dockerignore`
  4. 4Check COPY source paths are relative to the build context, not the Dockerfile
  5. 5For multi-stage, verify --from=<stage> references the correct stage name or index

>Fix

  1. 1Ensure COPY source files are within the build context directory
  2. 2Create or update .dockerignore to exclude node_modules, .git, build artifacts, etc.
  3. 3Order Dockerfile instructions to maximize cache hits: COPY package.json before COPY . .
  4. 4Use `docker build -f Dockerfile .` from the correct context directory
  5. 5For multi-stage builds, name stages with AS and reference correctly: `COPY --from=builder`

*Prevention

  • Always create a .dockerignore file that mirrors .gitignore plus build artifacts
  • Keep Dockerfiles simple and follow the official best practices
  • Use multi-stage builds to keep final images small
  • Test Dockerfile changes locally before pushing to CI
  • Use BuildKit for faster builds: `DOCKER_BUILDKIT=1 docker build`

Related Error Messages

COPY failed: file not found in build contextfailed to compute cache keySending build context to Docker daemonStep X/Y : COPYlstat: no such file or directory