Triggering a Docker image build on Google Cloud Build when pushing commits to a GitHub repository.
Create Google Cloud Build Configuration File
Create a cloudbuild.yaml
in the root folder:
substitutions:
_REGION: us-west1
_REPOSITORY: your-repo
_BRANCH_TAG: ${BRANCH_NAME//\//-} # Replace / with - in branch names
steps:
- id: my-app
name: gcr.io/cloud-builders/docker
args:
[
"build",
"--cache-from",
"${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-app:${_BRANCH_TAG}",
"-t",
"${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-app:${_BRANCH_TAG}",
"-t",
"${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-app:$SHORT_SHA",
"docker/my-blog/",
]
waitFor: ["-"]
# Cloud Build only pushes tags listed here
images:
- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-app:$SHORT_SHA
- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-app:${_BRANCH_TAG}
The above config will store your Docker images in Artifact Registry. If you want to push images to another region, simply rename us-west1-docker.pkg.dev
to something like asia-east1-docker.pkg.dev
.
ref:
https://cloud.google.com/build/docs/configuring-builds/create-basic-configuration
https://cloud.google.com/build/docs/building/store-artifacts-in-artifact-registry
Configure Google Cloud Build with Your GitHub Repository
Go to Google Cloud Dashboard > Google Cloud Build > Triggers > Create trigger:
- Region: Global
- Event: Push to a branch
- Source: 1st Gen
- Repository:
- Connect new repository
- Source code management provider: GitHub (Cloud Build GitHub App)
- Install Google Cloud Build GitHub app
- Only select repositories
- Branch:
^main$
- Type: Autodetected
- Location: Repository
That's it, now you could push some commits to your GitHub repository.
ref:
https://console.cloud.google.com/cloud-build/triggers
https://console.cloud.google.com/cloud-build/builds