Where to put .dockerignore?

Viewed 11144

Consider the following typical python project structure:

fooproject 
  - main.py
  - src/
  - test/
  - logs/
  - Dockerfile
  - .dockerignore
  - README.md

The .dockerfile should prevent test/ and logs/ directories from being included in the docker image.

test/
logs/

Contents of Dockerfile are

FROM ubuntu16.04

COPY . /app/
WORKDIR /app    
USER root    
RUN pip install -r requirements.txt    
ENTRYPOINT ["main.py"]

However, when running through PyCharm's automatic docker integration, the test and logs directories are both copied into the container. The PyCharm run command ends up as follows:

7eb643d9785b:python -u /opt/project/main.py 

I've tried a few things to no avail, such as making a duplicate copy of .dockerignore at the directory above the rest of the app. For example:

COPY . /app/
COPY .dockerignore .dockerignore
WORKDIR /app

Wondering if it's possible that PyCharm's /opt/project is somehow interfering? So where exactly should .dockerignore be in a project like this?

Update

I shared the output of docker container inspect with BMitch, and he was able to find the solution. PyCharm was automatically mounting a volume in the container settings run config

enter image description here

1 Answers

The .dockerignore is used to control what files are included in the build context. This impacts the COPY and ADD commands in the Dockerfile, and ultimately the resulting image. When you run that image with a volume mount, e.g.:

        {
            "Type": "bind",
            "Source": "/home/adam/Desktop/Dev/ec2-data-analysis/grimlock",
            "Destination": "/opt/project",
            "Mode": "rw",
            "RW": true,
            "Propagation": "rprivate"
        },

That volume mount overrides the contents of the image for that container. All access to the path will go to your desktop directory rather than the image contents, and Linux bind mounts do not have a concept of the .dockerignore file.

When you run this image without the volume mount, you should see different behavior.


For anyone coming across this question in the future, the .dockerignore needs to be in the root of your build context. The build context is the directory you pass at the end of the build command, often a . or the current directory. If you enable BuildKit, it will first check for a Dockerfile.dockerignore where your Dockerfile path/name could be changed. And to test your .dockerignore, see this answer.

Related