How to ADD all files/directories except a hidden directory like .git in Dockerfile

DockerDockerfile

Docker Problem Overview


One of things we do often is to package all source code in Dockerfile when we build a Docker image.

ADD . /app

How can we avoid including the .git directory in simple way ?

I tried the Unix way of handling this using ADD [^.]* /app/

Complete sample:

docker@boot2docker:/mnt/sda1/tmp/abc$ find .
.
./c
./.git
./Dockerfile
./good
./good/a1
docker@boot2docker:/mnt/sda1/tmp/abc$ cat Dockerfile
FROM ubuntu

ADD [^.]* /app/ docker@boot2docker:/mnt/sda1/tmp/abc$ docker build -t abc . Sending build context to Docker daemon 4.096 kB Sending build context to Docker daemon Step 0 : FROM ubuntu ---> 04c5d3b7b065 Step 1 : ADD [^.]* /app/ d ---> 5d67603f108b Removing intermediate container 60159dee6ac8 Successfully built 5d67603f108b docker@boot2docker:/mnt/sda1/tmp/abc$ docker run -it abc root@1b1705dd66a2:/# ls -l app total 4 -rw-r--r-- 1 1000 staff 30 Jan 22 01:18 Dockerfile -rw-r--r-- 1 root root 0 Jan 22 01:03 a1 -rw-r--r-- 1 root root 0 Jan 22 00:10 c

And secondly, it will lose the directory structure, since good\a1 gets changed to a1.

Related source code in Docker is https://github.com/docker/docker/blob/eaecf741f0e00a09782d5bcf16159cc8ea258b67/builder/internals.go#L115

Docker Solutions


Solution 1 - Docker

You may exclude unwanted files with the help of the .dockerignore file

Solution 2 - Docker

> How can we avoid including the .git directory in simple way ?

Just create a file called .dockerignore in the root context folder with the following lines

**/.git
**/node_modules

With such lines Docker will exclude directories .git and node_modules from any subdirectory including root. Docker also supports a special wildcard string ** that matches any number of directories (including zero).

> And secondly, it will lose the directory structure, since good\a1 gets changed to a1

With .dockerignore it won't

$ docker run -it --rm sample tree /opt/
/opt/
├── Dockerfile
├── c
│   └── no_sslv2.patch
└── good
    └── a1
        └── README

3 directories, 3 files

Reference to official docs: .dockerignore

Solution 3 - Docker

Add .dockerignore file in your root directory (syntax like the .gitignore file)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLarry CaiView Question on Stackoverflow
Solution 1 - DockerMykola GurovView Answer on Stackoverflow
Solution 2 - DockerALex_hhaView Answer on Stackoverflow
Solution 3 - Dockeruser6830821View Answer on Stackoverflow