docker/docker-py

Cannot build image with path outside build context.

DraqunTheWorker opened this issue · 1 comments

Hi.
I have a problem because there is no way to build image from pytest hooks function. The structure of my project looks like this

/
| -- requirements.txt
| -- docker
|    | -- service
|    |    | -- Dockerfile
| -- src
...
| -- tests
|     | -- integrations
|     |     | -- conftest.py
...

Python is in version 3.11, docker package in version 7.0.0.

So the pytest hook is in conftest file. In this hook I have a docker_client and try build image using Dockerfile for a service from docker/service/Dockerfile in which I have a COPY command like this COPY ../../requirements.txt /app.
And there is no way to force build command to copy this file. I tried few tricks:

image_tag="my-image"
os.chdir("../../")  # move to main directory
with open("docker/service/Dockerfile") as file_handler:
        image, logs = docker_client.images.build(
            fileobj=io.BytesIO(file_handler.read().encode("utf-8")),
            tag=image_tag,
        )
...

and

image_tag="my-image"
os.chdir("../../")  # move to main directory
image, logs = docker_client.images.build(
    path=".",
    docker="docker/service/Dockerfile",
    tag=image_tag,
)

and

image_tag="my-image"
os.chdir("../../")  # move to main directory
image, logs = docker_client.images.build(
    path="docker/service",
    tag=image_tag,
)

and

image_tag="my-image"
image, logs = docker_client.images.build(
    path="../../docker/service",
    tag=image_tag,
)

and there is no possible to force build command to work as a the following bash command

docker build --platform linux/amd64 -f ./docker/service/Dockerfile -t my-image .

it always fails with the following error

E               docker.errors.BuildError: COPY failed: forbidden path outside the build context: ../../requirements.txt ()

Can you propose any solution for that problem? Any help will be appreciated.
Best regards

You can do the same as you're doing for the CLI: use the project root as the build context and pass a path to the Dockerfile.

See https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.ImageCollection.build for details.

e.g. docker_client.images.build(path=".", dockerfile="./docker/service/Dockerfile", tag=image_tag).