.dockerignore is a docker ignore file similar to a .gitignore file. It contains all files and folders to exclude during building the docker image.

It is used to optimize container image size during the image build.

which files to ignore for docker

The files which are not required for building an image

  • package manager generated specific folders node_modules
  • logs
  • git metadata folders
  • file extension types using patterns

What is a Dockerignore file?

Dockerignore is a text configuration file that contains a set of lines, each line contains files or directories. These are ignored by the Docker engine during building an image.

Where should be Dockerignore?

.dockerignore file is placed in the build directory. It is available to read during the docker build command.

Ideally, It is best to use it inside the folder where the docker build command runs

How to create a sample Dockerignore?

Dockerignore file can be created using any text editor or vi editor

cat .dockerignore
or
\vi .dockerignore

or
nano .dockerignore

It creates a .dockerignore in the current directory.

Add each line to this file with the list of files or folders to ignore

# is a comment in this file

# node modules to ignore
node_modules/
# logs
logs/
# git  metadata ignore
.git

How can I exclude a sub-directory with a .dockerignore file

Subfolders paths are included in the .dockerignore file as given below

dist/lib/*

It ignores all the files inside dist/lib/** i.e 3rd level.

If you want to exclude multiple levels, you can include them as given below

dist/lib/*
dist/lib/*/*

ignore all .git folders in .dockerignore

.git is a folder created for every folder and subfolder of a git repository.

The folder can contain many levels. To match all levels of subfolders, We have to use the ** pattern.


# .git in all subfolders example
**/.git

dockerignore exclude a folder and include file types

The /main/* folder is ignored and it’s content is. yaml files inside the subfolders of the main folder are not ignored.

/main/*
!/main/*.yaml
!/main/**/*.yaml

dockerignore file example

Here is a sample example of a dockerignore file

# node_modules folder
node_modules/
npm-debug.log
yarn-debug.log


# node modules to ignore
node_modules/
# logs
logs/
# git  metadata ignore on every level of a directory
**/.git
# exclude the main folder and its files
/main/*

# include yaml file inside all levels of the main folder
!/main/*.yaml
!/main/**/*.yaml

# Ignore generated all class files
**/*.class

# Ignore files with extensions
*.scss