1

I have a project structure like the following

app/
   docker-compose.yml
   module1/
       Dockerfile
       module1.py
   module2/
       Dockerfile
       module2.py
   common/
       common_things.py

In my Dockerfile for module1 I have

COPY module1.py /app
COPY ../common /app/common

But Docker does not like this second line. Error is below

ERROR: Service 'module1' failed to build: COPY failed: Forbidden path outside the build context: ../common ()

How do I tell Docker, through Dockerfile or Docker-compose, that it is okay for module1 to grab files from ../common? I could symlink common so that module1 and module2 have common in their respective dirs but that feels like overkill...

Extra credit: What is best practice for sharing files across Docker containers? Perhaps there is another way that I am unaware of.

cjavier70
  • 483
  • 1
  • 4
  • 14
  • Check this question: https://stackoverflow.com/questions/27068596/how-to-include-files-outside-of-dockers-build-context Also this issue: https://github.com/moby/moby/issues/2745 – Emruz Hossain Nov 22 '18 at 04:04
  • If you need share files between containers, try using `-v` or `volumes` options to map host files/dir to your container. with volumes mapping, you don't need to rebuild your image whenever file changed. https://docs.docker.com/compose/compose-file/#volume-configuration-reference – Enix Nov 22 '18 at 09:03
  • Possible duplicate of [Making a dependencies container and mount its volumes on other containers](https://stackoverflow.com/questions/53324081/making-a-dependencies-container-and-mount-its-volumes-on-other-containers) – Siyu Nov 22 '18 at 12:28
  • 1
    This question is not about volumes as OP searches for a build-time solution. – Fabian Braun Nov 22 '18 at 13:24

1 Answers1

1

You can achieve it by passing the entire app directory as build-context.

The docker-compose.yml would look like this:

version: '3'
services:
  module1:
    build:
      context: ./
      dockerfile: module1/Dockerfile
...

The (first) Dockerfile would look like this:

...
COPY module1/module1.py /app
COPY common /app/common
...

Some further comments:

Normally you would publish common parts of your two docker images as a shared library. I'm not very familiar with python but I believe it would boil down to:

  • publish your common_things.py as a python package on some python repository, so that it can be installed through pip install
  • add a requirements.txt file in each of your Docker-images and refer to your python package inside it
  • run pip install -r requirements.txt during your Docker-build to install your common_things-package in the docker-image.

However, this might be overkill for your usecase, so I think your solution for sharing the file might be the good choice for you.

Fabian Braun
  • 3,612
  • 1
  • 27
  • 44