Build a Docker image automatically with Cloud Build in Google Cloud Platform

Learn basic CI/CD with GCP

Lynn Kwong
7 min readMar 30, 2021


In modern software development practice, it is common to dockerize our applications. Therefore, it will be convenient if a docker image can be automatically built when we push some code to the repository. This is part of the continuous integration/continuous deployment (CI/CD) practice. For example, if we want to schedule some jobs in Airflow, we can use the KubernetesPodOperator to run the docker image of our application. With Cloud Build, the docker image can be automatically built for us whenever we push some new code.

Photo by Nikin on Pixabay.

Cloud Build is a service that executes your builds on Google Cloud Platform’s infrastructure. Cloud Build can import source code from a variety of repositories or cloud storage spaces, execute a build to your specifications, and produce artifacts such as Docker containers.

With cloud build, you can write a build config file to provide instructions to Cloud Build on what tasks to perform. Cloud Build executes your build as a series of build steps, where each build step is run in a Docker container.

To build your Docker image using a build config file, we need to create a file named cloudbuild.yaml in the same directory that contains your application source code.

It is recommended to use the GCP Cloud Shell to follow the instructions in this article because the environment has been set up in the Cloud Shell and all commands needed such as docker and gcloud can be used directly. For demonstration purpose, we will use a very simple Dockerfile to build an image:

FROM alpine
CMD ["echo", "Hello World!"]

FROM sets the base docker image for subsequent instructions. alpine is a minimal Docker image based on Alpine Linux.

CMD specifies which command should be run when a container is started from your image.

To build the docker image directly in the Cloud Shell, we can run this command:

docker build -t helloworld:latest .

To run a container with the image built, run

docker run --rm helloworld



Lynn Kwong

I’m a Software Developer ( keen on sharing thoughts, tutorials, and solutions for the best practice of software development.