How to Use .dockerignore to Optimize Docker Builds
Use a
.dockerignore file in your Docker build context to list files and folders that Docker should ignore when building an image. This helps speed up builds and keeps images smaller by excluding unnecessary files.Syntax
The .dockerignore file uses simple patterns to specify files and directories to exclude from the Docker build context. Each line is a pattern matching files or folders. Blank lines and lines starting with # are ignored as comments.
Patterns can be:
node_modules- ignores the folder namednode_modules*.log- ignores all files ending with.logtemp/- ignores thetempfolder and its contents!important.log- negates ignore, soimportant.logis included even if*.logis ignored
dockerignore
.dockerignore # Ignore node modules folder node_modules # Ignore all log files *.log # Ignore temp folder temp/ # But include important.log !important.log
Example
This example shows a .dockerignore file that excludes node_modules and all .log files except keep.log. It speeds up the Docker build by not sending these files to the Docker daemon.
dockerfile
# .dockerignore node_modules *.log !keep.log # Dockerfile FROM alpine:3.18 COPY . /app WORKDIR /app RUN ls -la
Output
total 12
drwxr-xr-x 5 root root 4096 Apr 27 12:00 .
drwxr-xr-x 1 root root 4096 Apr 27 12:00 ..
-rw-r--r-- 1 root root 0 Apr 27 12:00 Dockerfile
-rw-r--r-- 1 root root 0 Apr 27 12:00 keep.log
-rw-r--r-- 1 root root 0 Apr 27 12:00 .dockerignore
Common Pitfalls
Common mistakes when using .dockerignore include:
- Forgetting to add
.dockerignorefile, causing large folders likenode_modulesto be sent to Docker, slowing builds. - Incorrect patterns that do not match intended files, e.g., missing trailing slash for folders.
- Using negation (
!) incorrectly, which can cause unexpected files to be included or excluded. - Not realizing that
.dockerignoreonly affects the build context sent to Docker, not files copied inside the container after build.
dockerignore
# Wrong: missing trailing slash means only folder named 'temp' is ignored, not contents
# temp
# Right: add trailing slash to ignore folder and contents
# temp/
Quick Reference
| Pattern | Effect |
|---|---|
| node_modules | Ignore folder named node_modules and its contents |
| *.log | Ignore all files ending with .log |
| temp/ | Ignore folder temp and everything inside |
| !important.log | Include important.log even if *.log is ignored |
| # comment | Lines starting with # are comments |
| Blank lines are ignored |
Key Takeaways
Always use a .dockerignore file to exclude unnecessary files and speed up Docker builds.
Patterns in .dockerignore match files and folders relative to the build context root.
Use trailing slashes to specify folders and negation (!) to include files explicitly.
Check your .dockerignore patterns carefully to avoid accidentally excluding needed files.
Remember .dockerignore only affects files sent to Docker during build, not runtime container files.