Implantação contínua com o Git usando o Cloud Build
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Use o Cloud Build para automatizar builds e implantações no
Knative serving usando o gatilho do Cloud Build
para criar e implantar automaticamente seu código sempre que novos commits forem enviados para
uma determinada ramificação de um repositório Git.
Quando você usa um gatilho do Cloud Build para criar contêineres, as
informações do repositório de origem são exibidas
no console do Google Cloud para o serviço após a implantação no
Knative serving.
Antes de começar
Você tem um repositório git com um Dockerfile ou a base do código é
escrita em uma das linguagens compatíveis com o
Google Cloud Buildpacks:
Go, Node.js, Python, Java ou .NET Core.
Enable the Cloud Build and Cloud Source Repositories
APIs.
Como configurar a implantação contínua a partir da interface do usuário do Knative serving
O procedimento varia um pouco dependendo se você está configurando
a implantação contínua em um novo serviço ou em um serviço existente. Clique na
guia apropriada para saber mais.
Novo serviço
Acesse o Knative serving no console do Google Cloud:
Preencha as Configurações do serviço com suas preferências.
Clique em Próxima.
Selecione Implantar continuamente novas revisões de um repositório de código-fonte.
Clique em Configurar com o Cloud Build.
Selecione o provedor e o repositório.
GitHub se você ainda não estiver autenticado, clique em Autenticar
e siga as instruções. Por padrão, a conexão de um repositório é feita
usando o app do GitHub para o Cloud Build. Como alternativa, é possível espelhar
o repositório do GitHub no Cloud Source Repositories. Para fazer isso, clique em
Opções avançadas e marque Espelhar repositório do GitHub usando o
Cloud Source Repositories.
Saiba mais.
Bitbucket se você ainda não estiver autenticado, clique em Autenticar
e siga as instruções.
Preencha as opções na etapa "Configuração do build":
Ramificação: indica qual código-fonte precisa ser usado ao executar o
gatilho. É possível colocar o regex
aqui. As ramificações correspondidas são verificadas automaticamente e podem ser vistas
abaixo da entrada. Se houver correspondência exata de uma
ramificação, o gatilho será executado automaticamente após a
criação.
Tipo de build
Se o repositório precisar ser criado com o Docker e ele contiver um
Dockerfile, selecione Dockerfile. Local de origem: indica o
local e o nome do Dockerfile. O diretório será usado como o
contexto de build do Docker. Todos os caminhos precisam estar relacionados ao diretório
atual.
Caso contrário, selecione Google Cloud Buildpacks. Use o
contexto de Buildpack para especificar o diretório e o Ponto de entrada
(opcional) para fornecer o comando que inicia o servidor. Por exemplo:
gunicorn -p :8080 main:app para Python,
java -jar target/myjar.jar para Java. Deixe em branco para usar
o comportamento padrão.
Clique em Salvar.
Verifique as configurações selecionadas.
Clique em Criar.
Você será redirecionado para a página Detalhes do serviço, em que poderá
acompanhar o progresso da configuração da implantação contínua.
Quando todas as etapas forem concluídas, observe as opções adicionais:
GitHub se você ainda não estiver autenticado, clique em Autenticar
e siga as instruções. Por padrão, a conexão de um repositório é feita
usando o app do GitHub para o Cloud Build. Como alternativa, é possível espelhar
o repositório do GitHub no Cloud Source Repositories. Para fazer isso, clique em
Opções avançadas e marque Espelhar repositório do GitHub usando o
Cloud Source Repositories.
Saiba mais.
Bitbucket se você ainda não estiver autenticado, clique em Autenticar
e siga as instruções.
Preencha as opções na etapa "Configuração do build":
Ramificação: indica qual código-fonte precisa ser usado ao executar o
gatilho. É possível colocar o regex
aqui. As ramificações correspondidas são verificadas automaticamente e podem ser vistas
abaixo da entrada. Se houver correspondência exata de uma
ramificação, o gatilho será executado automaticamente após a
criação.
Tipo de build
Se o repositório precisar ser criado com o Docker e ele contiver um
Dockerfile, selecione Dockerfile. Local de origem: indica o
local e o nome do Dockerfile. O diretório será usado como o
contexto de build do Docker. Todos os caminhos precisam estar relacionados ao diretório
atual.
Caso contrário, selecione Google Cloud Buildpacks. Use o
contexto de Buildpack para especificar o diretório e o Ponto de entrada
(opcional) para fornecer o comando que inicia o servidor. Por exemplo:
gunicorn -p :8080 main:app para Python,
java -jar target/myjar.jar para Java. Deixe em branco para usar
o comportamento padrão.
Clique em Salvar.
A página é recarregada e exibe o progresso da
configuração da implantação contínua.
Quando todas as etapas forem concluídas, observe as opções adicionais:
Anexar o gatilho do Cloud Build ao serviço do Knative serving.
Se você já tiver um gatilho do Cloud Build, poderá anexá-lo ao
serviço e aproveitar os recursos do console do Google Cloud na página
"Detalhes do serviço" (botão Editar implantação contínua e gráfico Histórico de builds).
Para isso, você precisa adicionar um rótulo com gcb-trigger-id como chave e
o identificador exclusivo do gatilho do Cloud Build como valor, e não o nome
dele. Veja as instruções para
configurar o rótulo.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-05-06 UTC."],[],[],null,["# Continuous deployment from Git using Cloud Build\n\nYou can use Cloud Build to automate builds and deployments to\nKnative serving by using [Cloud Build trigger](/build/docs/running-builds/automate-builds)\nto automatically build and deploy your code whenever new commits are pushed to\na given branch of a Git repository.\n\nWhen you use a Cloud Build trigger to build containers, the\n[source repository information is displayed](/kubernetes-engine/enterprise/knative-serving/docs/managing/revisions#build-source)\nin the Google Cloud console for your service after you deploy to\nKnative serving.\n\nBefore you begin\n----------------\n\n- You either have a git repository with a `Dockerfile` or your codebase is written in one of the languages supported by [Google Cloud's buildpacks](/docs/buildpacks/overview): Go, Node.js, Python, Java or .NET Core.\n-\n\n\n Enable the Cloud Build and Cloud Source Repositories\n APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=sourcerepo.googleapis.com,cloudbuild.googleapis.com)\n\nSetting up continuous deployment from the Knative serving user interface\n------------------------------------------------------------------------\n\nThe procedure varies slightly depending on whether you are setting up\ncontinuous deployment on a new service or on an existing service. Click the\nappropriate tab to learn more. \n\n### New service\n\n1. Go to Knative serving in the Google Cloud console:\n\n [Go to Knative serving](https://console.cloud.google.com/kubernetes/run)\n2. Click **Create service**.\n\n3. Fill the *Service Settings* with your preferences.\n\n4. Click **Next**.\n\n5. Select **Continuously deploy new revisions from a source repository**.\n\n6. Click **Set up with Cloud Build**.\n\n7. Select the provider and the repository.\n\n - *GitHub* - if you are not yet authenticated, click **Authenticate** and follow the instructions. By default, connecting a repository is done via the Cloud Build GitHub app. Alternatively, you can mirror your GitHub repository in Cloud Source Repositories. To do so, click *Advanced option* and check *Mirror GitHub repository using\n Cloud Source Repositories* [Learn more](/build/docs/automating-builds/create-github-app-triggers?#different_types_of_github-based_triggers)\n - *Bitbucket* - if you are not yet authenticated, click **Authenticate** and follow the instructions.\n - [*Cloud Source Repositories*](/source-repositories/docs)\n\n8. Click **Next**.\n\n9. Fill the options in Build Configuration step:\n\n - *Branch* - indicates what source should be used when running the trigger. You can put the [regex](https://github.com/google/re2/wiki/Syntax) here. Matched branches are automatically verified: you can see them below the input. Note that if exactly one branch is matched, the trigger will be automatically executed after the creation.\n - *Build Type*\n\n - If your repository should be built using Docker and it contains a\n Dockerfile, select **Dockerfile** . **Source location** indicates the\n location and name of the Dockerfile. This directory will be used as the\n Docker build context. All paths should be relative to the current\n directory.\n\n - Otherwise, select **Google Cloud Buildpacks** . Use\n **Buildpack context** to specify the directory and **Entrypoint**\n (optional) to provide the command to start the server. Example:\n `gunicorn -p :8080 main:app` for Python,\n `java -jar target/myjar.jar` for Java. Leave it blank to use\n [default behavior](/docs/buildpacks/service-specific-configs).\n\n10. Click **Save**.\n\n11. Verify the selected settings.\n\n12. Click **Create**.\n\n13. Note that you are redirected to the *Service Details* page, where you can\n track the progress of your Continuous Deployment set up.\n\n14. Once all steps are completed, note additional options:\n\n - Edit Continuous Deployment button.\n - Build History.\n - Source details in the [*Revision Details* section](/kubernetes-engine/enterprise/knative-serving/docs/managing/revisions#viewing_revision_details).\n\n### Existing service\n\n1. Go to Knative serving in the Google Cloud console:\n\n [Go to Knative serving](https://console.cloud.google.com/kubernetes/run)\n2. Locate the service in the services list, and click on it.\n\n3. Click **Set up Continuous Deployment**.\n\n4. Select the provider and the repository.\n\n - *GitHub* - if you are not yet authenticated, click **Authenticate** and follow the instructions. By default, connecting a repository is done via the Cloud Build GitHub app. Alternatively, you can mirror your GitHub repository in Cloud Source Repositories. To do so, click *Advanced option* and check *Mirror GitHub repository using\n Cloud Source Repositories* [Learn more](/build/docs/automating-builds/create-github-app-triggers?#different_types_of_github-based_triggers)\n - *Bitbucket* - if you are not yet authenticated, click **Authenticate** and follow the instructions.\n - [*Cloud Source Repositories*](/source-repositories/docs)\n\n5. Click **Next**.\n\n6. Fill the options in Build Configuration step:\n\n - *Branch* - indicates what source should be used when running the trigger. You can put the [regex](https://github.com/google/re2/wiki/Syntax) here. Matched branches are automatically verified: you can see them below the input. Note that if exactly one branch is matched, the trigger will be automatically executed after the creation.\n - *Build Type*\n\n - If your repository should be built using Docker and it contains a\n Dockerfile, select **Dockerfile** . **Source location** indicates the\n location and name of the Dockerfile. This directory will be used as the\n Docker build context. All paths should be relative to the current\n directory.\n\n - Otherwise, select **Google Cloud Buildpacks** . Use\n **Buildpack context** to specify the directory and **Entrypoint**\n (optional) to provide the command to start the server. Example:\n `gunicorn -p :8080 main:app` for Python,\n `java -jar target/myjar.jar` for Java. Leave it blank to use\n [default behavior](/docs/buildpacks/service-specific-configs).\n\n7. Click **Save**.\n\n8. The page reloads and displays the progress of the\n Continuous Deployment setup.\n\n9. Once all steps are completed, note additional options:\n\n - Edit Continuous Deployment button.\n - Build History.\n - Source details in the [*Revision Details* section](/kubernetes-engine/enterprise/knative-serving/docs/managing/revisions#viewing_revision_details).\n\nSetting up continuous deployment manually\n-----------------------------------------\n\nRefer to\n[Setting up continuous deployment manually](/build/docs/deploying-builds/deploy-cloud-run)\nif you need to use a manual procedure and not the UI.\n\nAttach existing Cloud Build trigger to Knative serving service.\n---------------------------------------------------------------\n\nIf you already have an existing Cloud Build trigger, you can attach it to\nthe service and take advantage of Google Cloud console features in the Service\nDetails page: **Edit Continuous Deployment** button and **Build History** chart.\n\nTo do so, you have to add a label with \u003cvar translate=\"no\"\u003egcb-trigger-id\u003c/var\u003e as a key and\nthe unique identifier of the Cloud Build trigger as value (not the trigger\nname). See [instructions](/kubernetes-engine/enterprise/knative-serving/docs/configuring/labels#set-labels) for\nsetting up the label."]]