Docker: provide custom context in python-sdk
Question:
I am trying to emulate the following CLI command using the docker python-sdk:
docker build -t mytag -f path_to_my_dockerfile/Dockerfile ../../../.
So in this case I want it to build the Dockerfile using the build context ../../../.
.
I tried using the python-sdk for docker but it seems each time the build context is not the right one, I tried various combinations like :
import docker
client = docker.from_env()
clients.images.build(path="../../../.", fileobj="path_to_my_dockerfile/Dockerfile", tag="mytag")
but nothing seems to work. Looking into the docker-py repo is not helping.
Answers:
You just need to provide the dockerfile
argument:
clients.images.build(
path="../../../.",
dockerfile="path_to_my_dockerfile/Dockerfile",
tag="mytag"
)
Note that the dockerfile
should be relative to path
, not your current working directory.
If you have dockerfile and context relative to your current working directory, you may be able to compute the relative path with something like this:
dockerfile = pathlib.Path(os.path.normpath(dockerfile)).absolute()
context = pathlib.Path(os.path.normpath(context)).absolute()
path = dockerfile.relative_to(context)
Alternatively, you can also provide a custom build context, by creating a tarfile yourself with custom_context
. This is the most flexible way, as you don’t even need a filesystem that way.
I am trying to emulate the following CLI command using the docker python-sdk:
docker build -t mytag -f path_to_my_dockerfile/Dockerfile ../../../.
So in this case I want it to build the Dockerfile using the build context ../../../.
.
I tried using the python-sdk for docker but it seems each time the build context is not the right one, I tried various combinations like :
import docker
client = docker.from_env()
clients.images.build(path="../../../.", fileobj="path_to_my_dockerfile/Dockerfile", tag="mytag")
but nothing seems to work. Looking into the docker-py repo is not helping.
You just need to provide the dockerfile
argument:
clients.images.build(
path="../../../.",
dockerfile="path_to_my_dockerfile/Dockerfile",
tag="mytag"
)
Note that the dockerfile
should be relative to path
, not your current working directory.
If you have dockerfile and context relative to your current working directory, you may be able to compute the relative path with something like this:
dockerfile = pathlib.Path(os.path.normpath(dockerfile)).absolute()
context = pathlib.Path(os.path.normpath(context)).absolute()
path = dockerfile.relative_to(context)
Alternatively, you can also provide a custom build context, by creating a tarfile yourself with custom_context
. This is the most flexible way, as you don’t even need a filesystem that way.