Search code examples
pythondockergoogle-container-registry

Upload docker image to GCR through python


I'm working on a python code where I need to build a docker image and push it to GCR (Google Container Registry). I'm able to create a docker image using Docker SDK for Python however I'm not able to find out a way to push it to gcr. I was looking into docker_client.images.push()method but I don't see a way to connect to gcr using this method. I can build the docker image using docker_client.images.build() but not able to find any way to push it to google container registry. There are ways to push it to docker registry but I need specific to gcr.

I have already implemented this using google cli or through Azure DevOps however I'm trying to do the same using python application.

Any help/suggestion is appreciated.


Solution

  • This seems to have worked for me using the Docker SDK:

    import docker
    
    client  = docker.from_env()
    
    image, logs = client.images.build(path="<path/to/your/docker-repo>")
    
    image_dest = "gcr.io/<your-gcp-project>/<your-repo-name>"
    
    image.tag(image_dest)
    
    client.api.push(image_dest)
    

    I also had to add permissions with gcloud auth configure-docker.