DEV Community

JohnDivam
JohnDivam

Posted on

Why You Should Never Skip .dockerignore

Why You Should Never Skip .dockerignore

When I started using Docker, I wrote a Dockerfile, ran docker build, and moved on. It worked, so I never thought about it again. Later I noticed my builds were slow and my images were bigger than they should be. The cause was a small file I had never created: .dockerignore.

What is it?

A .dockerignore file tells Docker which files to leave out when you build an image. It works like .gitignore, but for Docker. When you run docker build, Docker first sends your whole project folder (the "build context") to the Docker engine. Anything listed in .dockerignore is not sent.

Why it matters

1. Faster builds.
Think about node_modules, vendor, or .git. These folders can be hundreds of megabytes. Without .dockerignore, Docker copies all of it on every build, even if your Dockerfile never uses it. With the file in place, the build starts almost right away.

2. Smaller images.
When you write COPY . ., everything in the folder goes into the image. That includes logs, cache, test files, and editor settings. A smaller image is faster to push, pull, and deploy.

3. Better security.
This one is the most important. Your project folder may contain .env files, private keys, or passwords. If you copy them into an image, they stay there. Anyone who can pull the image can read them. Ignoring these files keeps secrets out.

4. Fewer strange bugs.
Here is a real example. You install dependencies on your Windows machine, then build a Linux image. If your local node_modules gets copied into the image, it can overwrite the clean one installed inside Docker. Native packages then break, and the error messages make no sense. Ignoring node_modules fixes this.

5. Better layer caching.
Docker reuses a layer if nothing in it has changed. If a log file or a cache file changes on every run and gets copied into the image, the cache is broken and Docker rebuilds everything. Ignoring those files keeps the cache working.

A simple example

For a Node project:

node_modules
.git
.env
.env.*
dist
npm-debug.log
Dockerfile
.dockerignore
Enter fullscreen mode Exit fullscreen mode

For a PHP project, you would ignore vendor, var, and local .env files instead.

A few tips

  • Do not ignore files your build needs, like package.json or composer.json.
  • Keep your lock files. They make builds repeatable.
  • Create the file on day one, not after problems start.
  • Review it from time to time as the project grows.

Final thoughts

.dockerignore takes two minutes to write, and it saves you from slow builds, large images, leaked secrets, and confusing errors. It is one of the easiest improvements you can make to a Docker setup. If your project does not have one yet, add it today.

Top comments (0)