Skip to content
Advertisement

Why isn’t my .Dockerignore file ignoring files?

When I build the container and I check the files that should have been ignored, most of them haven’t been ignored.

This is my folder structure.

JavaScript

Let’s say i want to ignore the __pycache__ & data(data will be created with the docker-compose up command, when creating the container) folders and the .gitignore & .env files.

I will ignore these with the next .dockerignore file

JavaScript

The final result is that only the git & .env files have been ignored. The data folder hasn’t been ignored but it’s not accesible from the container. And the __pycache__ folders haven’t been ignored either.

Here are the docker files.

docker-compose.yml

JavaScript

Dockerfile

JavaScript

Advertisement

Answer

You’re actually injecting your source code using volumes:, not during the image build, and this doesn’t honor .dockerignore.

Running a Docker application like this happens in two phases:

  1. You build a reusable image that contains the application runtime, any OS and language-specific library dependencies, and the application code; then
  2. You run a container based on that image.

The .dockerignore file is only considered during the first build phase. In your setup, you don’t actually COPY anything in the image beyond the requirements.txt file. Instead, you use volumes: to inject parts of the host system into the container. This happens during the second phase, and ignores .dockerignore.

The approach I’d recommend for this is to skip the volumes:, and instead COPY the required source code in the Dockerfile. You should also generally indicate the default CMD the container will run in the Dockerfile, rather than requiring it it the docker-compose.yml or docker run command.

JavaScript

This means, in the docker-compose.yml setup, you don’t need volumes:; the application code is already inside the image you built.

JavaScript

This approach also means you need to docker-compose build a new image when your application changes. This is normal in Docker.

For day-to-day development, a useful approach here can be to run all of the non-application dependencies in Docker, but the application itself outside a container.

JavaScript

Doing this requires making the database visible from outside Docker (via ports:), and making the database location configurable (probably via environment variables, set in Compose with environment:).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement