Docker Best Practices

Chapter 1 · Practice 4 of 5

Add a .dockerignore file to shrink the build context

From Writing the Dockerfile

Why it matters

Everything in the build context is sent to the builder, and COPY . . copies all of it into the image. Without a .dockerignore, that includes:

  • node_modules and build output such as dist
  • the .git folder and test fixtures
  • worst of all, local .env files with real secrets

The .dockerignore file uses syntax similar to .gitignore. Add it in the same commit as the Dockerfile so the two never drift apart.

To check it, look at the "transferring context" size in the build output: it should be a few megabytes for most apps, not hundreds.

Example

Code
.git
node_modules
dist
coverage
.env
.env.*
*.log
Dockerfile
compose.yaml