Build context

2 snippets in Docker

DKDocker

.dockerignore - Exclude Build Context

DK · Dockerfile
Syntax
# .dockerignore file
pattern
dir/
Example
node_modules
.git
*.md
.env
dist
.DS_Store
coverage

Note Place this file next to your Dockerfile. Without it, Docker sends everything in the build context to the daemon, including node_modules (hundreds of MB), .git history, and possibly secrets in .env files. This is one of the highest-impact optimizations you can make.

Build Configuration

DK · Docker Compose
Syntax
services:
  api:
    build:
      context: <path>
      dockerfile: <file>
      args:
        KEY: value
Example
services:
  api:
    build:
      context: .
      dockerfile: docker/Dockerfile.prod
      args:
        NODE_VERSION: 20
    image: myapp:latest

Note Setting both build and image means Compose builds and tags the result with that image name. The context path is relative to the compose file location.

Frequently asked questions

How does Docker handle build context?
Docker covers this with 2 copy-ready snippets on this page. The ".dockerignore - Exclude Build Context" snippet in Docker uses `# .dockerignore file`.
Which command does the Docker example use?
The ".dockerignore - Exclude Build Context" snippet uses `# .dockerignore file`, from the Dockerfile section of the Docker cheat sheet.
What other Docker snippets are shown for "build context"?
Besides ".dockerignore - Exclude Build Context", this page also shows "Build Configuration".
Is there anything to watch out for?
Yes. For ".dockerignore - Exclude Build Context": Place this file next to your Dockerfile. Without it, Docker sends everything in the build context to the daemon, including node_modules (hundreds of MB), .git history, and possibly secrets in .env files. This is one of the highest-impact optimizations you can make.