DEV Community

Alex Mammay
Alex Mammay

Posted on

Effective Go on GCP: Lean containers with ko on cloud build

What is ko?

ko is a technology that allows for building simple go applications into a container.

As long as the application does not need any os level package dependencies, ko is an easy and streamlined way to create
simple go applications as container. To read more check out the github repo for ko.

Using ko on gcp

We will focus on using cloud build, gcr and cloud run for our usage of ko in this example. There is a couple extra steps
involved in being able to use ko on cloud build, but the process should be straight forward.

Using the cloud-builders-community repo, we will grab the ko builder and run it through our projects cloud build
pipeline. I have this step in my makefile

.PHONY: setup-ko-gcr
    git clone --depth=1;
    gcloud builds submit ./cloud-builders-community/ko --config=./cloud-builders-community/ko/cloudbuild.yaml
    rm -rf ./cloud-builders-community
Enter fullscreen mode Exit fullscreen mode

Now when this is done, we will have the ko builder available to us under our private gcr repo

Next we will look at our applications cloudbuild.yaml file.

  #  using our ko builder we will build our application that lives in ./cmd/ko
  - name:$PROJECT_ID/ko
    entrypoint: /bin/sh
      - '$PROJECT_ID'
    # we write the result of ko publish to a txt file so we can persist the variable between steps
      - -c
      - |
        echo $(/ko publish --preserve-import-paths ./cmd/ko) > ./ko_container.txt || exit 1

  # Deploy container image to Cloud Run
  - name: ''
    entrypoint: /bin/bash
      - -c
      - |
        gcloud run deploy ko \
        --image=$(cat ./ko_container.txt) \
        --region=us-central1 \

Enter fullscreen mode Exit fullscreen mode

From us running gcloud builds submit --config=./cmd/ko/cloudbuild.yaml we will have our image uploaded to gcr and
deployed to cloud run!

You can view the full reference repo here

Top comments (2)

slimpython profile image
Abhi Raj

can't we use anything else?

amammay profile image
Alex Mammay

I don’t see why not, ko is just another way to get the job done!