Running gcloud in a docker container

I wanted to run Google's gcloud tool in a container. In addition to wanting to use gcloud in some CI/CD scripts, it's a rather large package and is updated quite frequently. Rather than run it locally on a development box, let's move execution into a container.

Google provides gcloud in a container on Docker Hub: google/cloud-sdk. But to use it, we need to create a persistent volume to store the authentication secrets and settings across invocations. This post was inspired by https://blog.scottlowe.org/2018/09/13/running-gcloud-cli-in-a-docker-container/ who showed me the details of passing a volume with the settings/secrets to the gcloud container.

Step 1: create a docker volume or local directory to hold the secrets. I used to use a local directory /app/secrets/gcloud (replace that with a directory of your choosing!) but now use a volume (volumes are more easy to work with on Docker Desktop for Windows).

For the directory:

mkdir /app/secrets/gcloud

Or, for the volume:

docker volume create gcloud

Step 2: Initialize gcloud

docker run --rm -it -v /app/secrets/gcloud:/root/.config/gcloud google/cloud-sdk gcloud init

or, for the volume (note how we just replace the directory name with the volume name).

docker run --rm -it -v gcloud:/root/.config/gcloud google/cloud-sdk gcloud init

Step 3: Now run any gcloud commands of your choosing. Here I manually test a Google Cloud Build job. Notice how I mount the code inside the gcloud contiainer on /app

docker run --rm -it -v /app/secrets/gcloud:/root/.config/gcloud -v /my/src/dir:/app google/cloud-sdk gcloud builds submit --config /app/cloudbuild.yaml /app

Or here you can login to Google's Container Registry on the host using an authentication token generated by gcloud (tested on docker for Linux and Docker Desktop for Windows)

docker run --rm -it -v gcloud:/root/.config/gcloud google/cloud-sdk gcloud auth print-access-token | docker login -u oauth2accesstoken --password-stdin https://us.gcr.io
Contact Us