How to Specify Dockerfile for gcloud builds submit

gcloud builds submit command submits a build to the GCP Cloud Build service and uses the Dockerfile from the build context. Sometimes, we may want to specify the Dockerfile while running the command. For instance, in one of my projects, I have Dockerfile.stage and Dockerfile.prod that I want to use separately with gcloud builds submit but there is no flag to pass a custom Dockerfile path/name.

To solve this, we can specify a build configuration file (YAML or JSON) for production and staging respectively and then pass them to the --config flag. So in my case, I created a cloudbuild-prod.yaml and cloudbuild-stage.yaml that would refer to Dockerfile.prod and Dockerfile.stage respectively. This is how the cloud build config files looked like:

steps:
# Docker image to be created
- name: "gcr.io/cloud-builders/docker"
  args:
  - build
  - "--tag=[ARTIFACT_REGISTRY_URL]"
  - "--file=./[DOCKERFILE]"
  - .
# Docker image to be pushed (same name as the step above)
images:
- "[ARTIFACT_REGISTRY_URL]"

The placeholders look like this:

  • ARTIFACT_REGISTRY_URL – Eg: us-central1-docker.pkg.dev/[PROJECT_ID]/[REPOSITORY_NAME]/[IMAGE_NAME]
  • DOCKERFILEDockerfile.prod or Dockerfile.stage

Finally, run the command with the config files passed like this:

$ gcloud builds submit --config=cloudbuild-prod.yaml
# or
$ gcloud builds submit --config=cloudbuild-staging.yaml

Leave a Reply

Your email address will not be published. Required fields are marked *