change198
change198

Reputation: 2065

How to build local docker image using python API with custom tag name

I have this script:

import docker
import os

localtag = "mypersonaltag"

client = docker.from_env()
dockerfile_path = os.path.dirname(os.getcwd())
print(dockerfile_path)

fname = dockerfile_path + "/Dockerfile"
path = os.path.dirname(fname)
image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag='localtag', rm=True)
print(image)

If I execute this script, it creates and build local docker image with tag name as localtag, but not as mypersonaltag. I have tried all other possible way like below, have a look at tag parameter. and it's throwing error.

image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)

or
image, build_log = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag={localtag}, rm=True)

but the strange thing, this [image, build_log = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)] command works perfectly thru python editor while using python script it gives error. No idea why? But as soon as I give quotes around the tags the python script which was breaking now working fine.

>>> tag  = "test02"
>>> image, build_log  = client.images.build(path=path, dockerfile='Dockerfile', tag=tag, rm=True)
>>> print(image)
<Image: 'local_tag:latest', 'localtag:latest', 'test01:latest', 'test02:latest'>

Upvotes: 2

Views: 1370

Answers (1)

404pio
404pio

Reputation: 1032

image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)

It's problem with passing variable to function, remove quotes around localtag

If you pass variable in such way tag={localtag}, then you are telling to python: "Hey take may variable, put it inside set, and pass this set to function". Probably you would try f"{localtag}" which uses fstring construction (requires python3.6).

--edit--

Please show us, how do you invoke your script? And what is the error?

Upvotes: 1

Related Questions