.dockerignore
- Docker & Kubernetes course
- Beginner
- Lesson 29/82
- 4 min
Learn to filter build context with .dockerignore.
.dockerignore
.dockerignore lists the files to exclude from the context with .gitignore-like patterns. The context shrinks, the build speeds up, and secret files (.env) are kept from accidentally entering the image:
# .dockerignore
.git
node_modules
*.log
.env
Dockerfile
!README.md # ! exception: include this anywayWhy is node_modules excluded?
The local node_modules is both very large and may be compiled for the host operating system (e.g. native modules compiled on macOS don't work in a Linux container). The right way is to install the dependencies inside the image with npm ci:
COPY package*.json ./
RUN npm ci --omit=dev
COPY . . # thanks to .dockerignore, the local node_modules doesn't comePractice Write a .dockerignore
Write the contents of a .dockerignore for a Node.js project: exclude .git, node_modules, .env and all .log files.
Starter code
# buraya yazSample solution
.git
node_modules
.env
*.logExpected output
[+] Building 1.1s => [internal] load build context => => transferring context: 18.42kB
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main reason to add the .env file to .dockerignore?
- To speed up the build
- To turn off environment variables
- To delete the file
- To keep passwords from entering the image layers Correct answer
Explanation: Anyone who pulls the image can read the files in its layers.
2 Exclude all log files.
____.log
*.log
Explanation: * matches any sequence of characters.
3 Match the patterns.
| Term | Meaning |
|---|---|
.git |
Version history |
*.log |
All log files |
!README.md |
Exception |
.env |
Secret values |