Search code examples
dockerdocker-composedockerfile

Docker Ignore is not woking well with docker compose and my file structure


I'am setting up a new dockerfile and docker-compose.yml. I'll below show first my file structure with rails and I want to use a new .dockerignore to ignore node_modules, .git .

my docker version is: Docker version 18.09.0, build 4d60db4

my docker-compose.yml than I use is v3

Root Directory

- Gemfile
- app
- bin
- cable
- db
- config
- lib
- node_modules
- public
- vendor
- docker
  - app
    - Dockerfile
- .git
- .gitignore
- .dockerignore
- docker-compose.yml

docker/app/Dockerfile

FROM ruby:2.3.1
ARG RAILS_ROOT
RUN mkdir -p $RAILS_ROOT
WORKDIR $RAILS_ROOT
COPY . .

docker-compose.yml


version: '3'
services:
  app:
    build: &build_core
      context: .
      dockerfile: ./docker/app/Dockerfile
      args:
        - APP_NAME=myappname
        - RAILS_ROOT=/var/www/${APP_NAME}_web
        - RAILS_ENV=development
        - RAILS_SERVE_STATIC_FILES=true
        - RAILS_LOG_TO_STDOUT=true
        - BUNDLE_OPTIONS=
        - NPM_OPTIONS=
    image: custom-web:1.0
    container_name: app
    volumes:
      - .:/var/www/${APP_NAME}_web
    env_file:
      - .env
    environment:
      RAILS_ROOT: "/var/www/${APP_NAME}_web"

.dockerignore


.git/
node_modules/

I built my image with the next command

docker-compose build app

When I look at the container, the file files are still copying to my container

maybe is the context or where I should put my .dockerignore also I put my .dockerignore into docker/app/.dockerignore and I have the same problem.


Solution

  • At build time, the directive COPY . . (inside the Dockerfile) correctly copies all files not listed in .dockerignore in $RAILS_ROOT (inside the image). No problem here (check that by running docker run --rm custom-web:1.0 ls -al).

    But here you run docker-compose to start the container, and you have defined a volume :

    volumes:
        - .:/var/www/${APP_NAME}_web
    

    That means that files from the same directory as docker-compose.yml are shared between the host and the container. That's why you find all files (even those listed in .dockerignore) in $RAILS_ROOT (workdir of custom-web:1.0 image) after starting the container via docker-compose.

    If you really need to share files between your host and the container (via a volume), I'll suggest you to mount the current directory in another location than the one specified in your Dockerfile, like :

    volumes:
        - .:/${APP_NAME}_web
    

    Otherwise, using COPY . . and a volume is redundant here.