How to exclude files from being added to docker image

TL;DR – use .dockerignore file, Docker’s equivalent of .gitignore for git


When building docker images, minimizing the size of the image is the goal. During building docker images with Dockerfile, especially with in a git repository, we might unintentionally add all the files into the docker image.

It is not uncommon to have something like “ADD . /app” in your Dockerfile. There are two ways to prevent this

  • Explicitly add only the files you need to Dockfile
  • Use .dockerignore file

A typical .dockerignore files in a git repo directory might look like this –

daniel@hidmo:/tmp/myapp$ ls -al
total 56
drwxr-xr-x  4 daniel daniel 4096 Dec 17 17:51 .
drwxrwxrwt 20 root   root   4096 Dec 17 17:51 ..
-rwxr-xr-x  1 daniel daniel  338 Dec 17 17:41 build-image.sh
drwxr-xr-x  2 daniel daniel 4096 Dec 17 17:41 .cache
-rw-r--r--  1 daniel daniel  245 Dec 17 17:41 Dockerfile
-rw-r--r--  1 daniel daniel  102 Dec 17 17:51 .dockerignore
drwxr-xr-x  8 daniel daniel 4096 Dec 17 17:52 .git
-rw-r--r--  1 daniel daniel    6 Dec 17 17:51 .gitignore
-rw-r--r--  1 daniel daniel  133 Dec 17 17:41 README
-rw-r--r--  1 daniel daniel  181 Dec 17 17:41 requirements.txt
-rw-r--r--  1 daniel daniel 7871 Dec 17 17:41 web.py
-rw-r--r--  1 daniel daniel 7871 Dec 17 17:50 web.pyc
daniel@hidmo:/tmp/myapp$ cat .dockerignore 
# Exclude files from being added to docker image
.git
.gitignore
.cache
.pyc
Dockerfile
README
readme

References

https://docs.docker.com/engine/reference/builder/#dockerignore-file