Dockerfile build from parent directory

11,256

Solution 1

There is no problem. In Dockerfile you cant get out (access parent folder) of build context, not Dockerfile's folder.

Leave you structure as it was, and explicitly specify path to Dockerfile:

docker build -t app -f application-build/Dockerfile . 
docker build -t celery -f celery-build/Dockerfile . 

And inside your Dockerfiles remember that path is /application. So you can easily copy:

Dockerfile

...
COPY code /code
...

Solution 2

Supplementing grapes's answer with a Docker Compose equivalent to the docker build commands:

# docker-compose.yml
version: '3.7'

services:
  application:
    build:
      context: .
      dockerfile: application-build/Dockerfile

  celery:
    build:
      context: .
      dockerfile: celery-build/Dockerfile
# Run this command in the directory of your `docker-compose.yml` file
# (Which is this question's case would be /application/docker-compose.yml)
docker-compose build

When each Dockerfile builds, it will use /application as its build context.

Share:
11,256
dben
Author by

dben

Updated on June 27, 2022

Comments

  • dben
    dben about 2 years

    I have a python application which uses celery workers which I would like to dockerise. Unfortunately, both python and Celery are using the same code base. Although they have to be separate containers for easier scaling. If I build them separately and run the containers it works fine. The problem starts when I introduce docker-compose, therefore I can't swap the dockerfiles out in the code folder and the containers need to be built from outside of the folder. The folder structure is the following:

    /application
        /application-build
           Dockerfile
        /celery-build
           Dockerfile
        /code
           application.py
           otherfiles.py
    

    I have been digging around for a bit now and unfortunately, as far as I know files from the parent directory can't be copied in the dockerfile. Although I would like to copy the same code into both of the containers. (Mind that the following dockerfiles are not the exact ones I use.)

    Dockerfile1:

    FROM python:3.6
    ADD /code .
    COPY requirements.txt requirements.txt
    RUN python3.6 -m pip install -r requirements.txt
    CMD ["python3.6", "application.py"]
    

    Dockerfile2:

    FROM python:3.6
    ADD /code .
    COPY /code/requirements.txt .
    RUN python3.6 -m pip install -r requirements.txt
    CMD ["celery","-A application.celery", "worker","work1@host"]
    

    One solution I see is to reorganise the folders so the code directory is always the child of the dockerfile's directory like so:

    /application
       /application-build
          Dockerfile
          /celery-build
             Dockerfile
             /code
                application.py
                otherfiles.py
    

    Although it doesn't look clever at all.