How to ignore folders to send in docker build context

Ibtesam Latif picture Ibtesam Latif · Aug 31, 2019 · Viewed 14.2k times · Source

I am facing an issue of large docker build context because of my project structure. In my root directory I have lib folder for common code and folders of micro-services. Now I want to build for miscroservice1 to include only lib folder and to ignore other microservices.

I am running docker build command in root folder because running command in microservice folder giving error Forbidden path outside the build context

rootFolder
-- lib
-- microservice1/Dockerfile
-- microservice2/Dockerfile
-- microservice3/Dockerfile

I have two solutions but didn't try for now

  1. To add symlinks for lib in my microservice folder
  2. To write script for each docker build to add lib folder in specific microservice folder and then run docker build.

I am trying the above two solutions. Can anyone suggest any best practice?

Answer

Minato picture Minato · Aug 31, 2019

You can create .dockerignore in your root directory and add

microservice1/
microservice2/
microservice3/

to it, just like .gitignore does during tracking files, docker will ignore these folders/files during the build.

Update

You can include docker-compose.yml file in your root directory, look at docker-compose for all the options, such as setting environment, running a specific command, etc, that you can use during the build process.

version: "3"
services:
  microservice1:
    build:
      context: .
      dockerfile: ./microservice1/Dockerfile
    volumes:
      - "./path/to/share:/path/to/mount/on/container"
    ports:
      - "<host>:<container>"
    links:
      - rootservice # defines a dns record in /etc/hosts to point to rootservice
  microservice2:
    build:
      context: .
      dockerfile: ./microservice2/Dockerfile
    volumes:
      - "./path/to/share:/path/to/mount/on/container"
    ports:
      - "<host>:<container>"
    links:
      - rootservice # defines a dns record in /etc/hosts to point to rootservice
      - microservice1
  rootservice:
    build:
      context: .
      dockerfile: ./Dockerfile
    volumes:
      - "./path/to/share:/path/to/mount/on/container"
    ports:
      - "<host>:<container>"
    depends_on:
      - microservice1
      - microservice2
    ports:
      - "<host1>:<container1>"
      - "<host2>:<container2>"

This will be your build recipe for your microservices, you can now run docker-compose build to build all your images.