Use .dockerignore to prevent leaking secrets

One Paragraph Explainer

The Docker build command copies the local files into the build context environment over a virtual network. Be careful - development and CI folders contain secrets like .npmrc, .aws, .env files and other sensitive files. Consequently, Docker images might hold secrets and expose them in unsafe territories (e.g. Docker repository, partners servers). In a better world the Dockerfile should be explicit about what is being copied. On top of this include a .dockerignore file that acts as the last safety net that filters out unnecessary folders and potential secrets. Doing so also boosts the build speed - By leaving out common development folders that have no use in production (e.g. .git, test results, IDE configuration), the builder can better utilize the cache and achieve better performance

Code Example – A good default .dockerignore for Node.js

.dockerignore

  1. **/node_modules/
  2. **/.git
  3. **/README.md
  4. **/LICENSE
  5. **/.vscode
  6. **/npm-debug.log
  7. **/coverage
  8. **/.env
  9. **/.editorconfig
  10. **/.aws
  11. **/dist

Code Example Anti-Pattern – Recursive copy of all files

Dockerfile

  1. FROM node:12-slim AS build
  2. WORKDIR /usr/src/app
  3. # The next line copies everything
  4. COPY . .
  5. # The rest comes here