이 페이지에서는 Cloud Build 빌드의 속도를 높이는 모범 사례를 확인할 수 있습니다.
간소화된 컨테이너 빌드
애플리케이션을 컨테이너화할 때 런타임에 필요하지 않은 파일(예: 빌드타임 종속 항목 및 중간 파일)이 실수로 컨테이너 이미지에 포함될 수 있습니다. 이렇게 불필요한 파일 때문에 컨테이너 이미지 크기가 커지고, 이미지가 컨테이너 이미지 레지스트리와 컨테이너 런타임 사이를 이동할 때 시간과 비용이 추가로 발생할 수 있습니다.
컨테이너 이미지 크기를 줄이려면 애플리케이션 빌드 단계를 애플리케이션을 빌드하는 데 사용하는 도구와 함께 런타임 컨테이너 어셈블리 단계에서 분리해야 합니다.
Kaniko 캐시는 후속 빌드에서 사용할 수 있는 Google의 Container Registry 같은 컨테이너 이미지 레지스트리에 중간 레이어를 저장하고 색인을 생성해서 컨테이너 빌드 아티팩트를 캐시하는 Cloud Build 기능입니다. 자세한 내용은 Kaniko 캐시 사용을 참조하세요.
캐시된 Docker 이미지 사용
Docker 이미지의 빌드 속도를 높이는 가장 쉬운 방법은 후속 빌드에 사용할 수 있는 캐시된 이미지를 지정하는 것입니다. 빌드 구성 파일에 --cache-from 인수를 추가하여 캐시된 이미지를 지정할 수 있습니다. 그러면 Docker가 해당 이미지를 캐시 소스로 사용하여 빌드합니다.
각 Docker 이미지는 누적 레이어로 구성됩니다. --cache-from을 사용하면 변경된 레이어의 모든 레이어가 빌드가 끝날 때까지 다시 빌드됩니다. 따라서 Docker 빌드의 초기 단계에서 레이어를 변경하는 경우 --cache-from을 사용하면 효과적이지 않습니다.
빌드에 항상 --cache-from을 사용하는 것이 좋지만 다음과 같은 주의사항에 유의해야 합니다.
캐시 소스로 사용할 이전에 빌드된 Docker 이미지가 필요합니다.
--cache-from은 Docker 빌드에만 사용할 수 있으며, 다른 종류의 아티팩트를 만드는 빌더에는 사용할 수 없습니다.
캐시된 이미지는 레지스트리에서 검색해야 하므로 빌드하는 데 걸리는 시간이 늘어날 수 있습니다.
다음 단계에서는 이전에 캐시된 이미지를 사용하여 빌드하는 방법을 설명합니다.
YAML
빌드 구성에 다음에 대한 지침을 추가합니다.
캐시된 이미지를 Container Registry에서 가져옵니다. 아래의 docker
pull 빌드 단계는 entrypoint를 bash로 설정하므로 사용자는 명령어를 실행하고 반환된 오류를 무시할 수 있습니다. 이 단계는 이미지를 처음으로 빌드할 때와 docker pull이 가져올 이미지가 없을 때 반드시 수행해야 합니다.
캐시된 이미지를 Container Registry에서 가져옵니다. 아래의 docker
pull 빌드 단계는 entrypoint를 bash로 설정하므로 사용자는 명령어를 실행하고 반환된 오류를 무시할 수 있습니다. 이 단계는 이미지를 처음으로 빌드할 때와 docker pull이 가져올 이미지가 없을 때 반드시 수행해야 합니다.
빌드 속도를 높이려면 이전 빌드의 결과를 다시 사용하세요. 이전 빌드의 결과를 Google Cloud Storage 버킷에 복사하고 결과를 사용하여 더 빠른 계산을 수행한 다음 새 결과를 버킷에 다시 복사할 수 있습니다. 빌드에 시간이 오래 걸리지만 생성되는 파일 수가 적어 Google Cloud Storage 안팎으로 해당 파일을 복사하는 데 시간이 걸리지 않는 경우에 이 방법을 사용하세요.
Docker 빌드에만 사용할 수 있는 --cache-from과 달리 Google Cloud Storage 캐싱은 Cloud Build에서 지원하는 모든 빌더에 사용할 수 있습니다.
Google Cloud Storage를 사용하여 디렉터리를 캐싱하려면 다음 단계를 따르세요.
YAML
빌드 구성 파일에 다음에 대한 지침을 추가합니다.
Google Cloud Storage 버킷에서 이전 빌드의 결과를 복사합니다.
해당 결과를 현재 빌드에 사용합니다.
새 결과를 버킷에 다시 복사합니다.
steps:-name:gcr.io/cloud-builders/gsutilargs:['cp','gs://mybucket/results.zip','previous_results.zip']# operations that use previous_results.zip and produce new_results.zip-name:gcr.io/cloud-builders/gsutilargs:['cp','new_results.zip','gs://mybucket/results.zip']
위의 빌드 구성을 사용하여 코드를 빌드합니다.
gcloud builds submit --config cloudbuild.yaml .
JSON
빌드 구성 파일에 다음에 대한 지침을 추가합니다.
Google Cloud Storage 버킷에서 이전 빌드의 결과를 복사합니다.
해당 결과를 현재 빌드에 사용합니다.
새 결과를 버킷에 다시 복사합니다.
{"steps":[{"name":"gcr.io/cloud-builders/gsutil","args":["cp","gs://mybucket/results.zip","previous_results.zip"]},{// operations that use previous_results.zip and produce new_results.zip},{"name":"gcr.io/cloud-builders/gsutil","args":["cp","new_results.zip","gs://mybucket/results.zip"]}]}
위의 빌드 구성을 사용하여 코드를 빌드합니다.
gcloudbuildssubmit--configcloudbuild.json.
불필요한 파일 업로드 방지
빌드를 트리거하면 코드 디렉터리는 Cloud Build가 사용할 수 있도록 업로드됩니다.
.gcloudignore 파일을 사용하여 빌드에 필요 없는 파일을 제외하면 업로드 시간을 최적화할 수 있습니다.
자주 제외되는 파일은 다음과 같습니다.
프로젝트 개발자용 문서와 샘플 코드
생성된 스캐폴딩 코드, 바이너리, *.jar 파일 또는 개발에 사용한 컴파일된 웹 애셋
벤더링된 로컬 개발용 타사 종속 항목
이를 위해 .gcloudignore 파일을 준비하려면 다음과 같은 내용으로 프로젝트 루트에서 파일을 생성해야 합니다.
.gitdistnode_modulesvendor*.jar
컴파일한 코드와 타사 종속 항목을 제외하면 빌드 프로세스의 일관성을 개선하고 개발 중인 코드를 실수로 배포하는 위험을 줄일 수도 있습니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-02-11(UTC)"],[[["\u003cp\u003eReduce container image size by separating the application build process from the assembly of the runtime container, which minimizes the inclusion of unnecessary files.\u003c/p\u003e\n"],["\u003cp\u003eUtilize Docker's \u003ccode\u003e--cache-from\u003c/code\u003e argument to speed up image builds by leveraging previously built images as a cache source, although this is most effective when changes occur in the later layers of a Docker build.\u003c/p\u003e\n"],["\u003cp\u003eEmploy Google Cloud Storage to cache build results across builds, enabling the reuse of previous outputs to accelerate current build processes, which is especially useful for time-consuming builds that produce small files.\u003c/p\u003e\n"],["\u003cp\u003eUse a \u003ccode\u003e.gcloudignore\u003c/code\u003e file to prevent the upload of unneeded files during the build process, such as documentation, third-party dependencies, and compiled binaries, reducing upload times and improving build consistency.\u003c/p\u003e\n"]]],[],null,["# Best practices for speeding up builds\n\nThis page provides best practices for speeding up Cloud Build builds.\n\nBuilding leaner containers\n--------------------------\n\nWhen you containerize an application, files that are not needed at runtime, such\nas build-time dependencies and intermediate files, can be inadvertently included\nin the container image. These unneeded files can increase the size of the\ncontainer image and add extra time and cost as the image moves between your\ncontainer image registry and your container runtime.\n\nTo help reduce the size of your container image, separate the building of the\napplication, along with the tools used to build it, from the assembly of the\nruntime container.\n\nFor more information, see [Building leaner containers](/build/docs/building-leaner-containers).\n\nUsing a cached Docker image\n---------------------------\n\nThe easiest way to increase the speed of your Docker image build is by\nspecifying a cached image that can be used for subsequent builds. You can\nspecify the cached image by adding the `--cache-from` argument in your build\nconfig file, which will instruct Docker to build using that image as a cache\nsource.\n\nEach Docker image is made up of stacked layers. Using `--cache-from` rebuilds\nall the layers from the changed layer until the end of the build; therefore\nusing `--cache-from` is not beneficial if you change a layer in the earlier\nstages of your Docker build.\n\nIt is recommended that you always use `--cache-from` for your builds, but keep\nthe following caveats in mind:\n\n- You need a previously built Docker image to cache from.\n- You can use `--cache-from` only for Docker builds; you cannot use it for builders that create other kind of artifacts.\n- The cached image must be retrieved from a registry, which may add to the time it takes to build.\n\nThe following steps explain how to build using a previously cached image: \n\n### YAML\n\n1. In your build config, add instructions to:\n\n - Pull the cached image from Container Registry. Notice that the `docker\n pull` build step below sets the `entrypoint` to `bash`, which allows you to run the command and ignore the returned error. This is required when you build an image for the first time, and `docker pull` does not have an existing image to pull.\n - Add a `--cache-from` argument to use that image for rebuilds.\n\n steps:\n - name: 'gcr.io/cloud-builders/docker'\n entrypoint: 'bash'\n args: ['-c', 'docker pull gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest || exit 0']\n - name: 'gcr.io/cloud-builders/docker'\n args: [\n 'build',\n '-t', 'gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest',\n '--cache-from', 'gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest',\n '.'\n ]\n images: ['gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest']\n\n where \\[IMAGE_NAME\\] is the name of your image.\n2. Build your image using the above build config:\n\n gcloud builds submit --config cloudbuild.yaml .\n\n### JSON\n\n1. In your build config, add instructions to:\n\n - Pull the cached image from Container Registry. Notice that the `docker\n pull` build step below sets the `entrypoint` to `bash`, which allows you to run the command and ignore any returned errors. This is required when you build an image for the first time, and `docker pull` does not have an existing image to pull.\n - Add a `--cache-from` argument to use that image for rebuilds.\n\n {\n \"steps\": [\n {\n \"name\": \"gcr.io/cloud-builders/docker\",\n \"entrypoint\": \"bash\",\n \"args\": [\"-c\", \"docker pull gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest || exit 0\"]\n },\n {\n \"name\": \"gcr.io/cloud-builders/docker\",\n \"args\": [\n \"build\",\n \"-t\",\n \"gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest\",\n \"--cache-from\",\n \"gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest\",\n \".\"\n ]\n }\n ],\n \"images\": [\"gcr.io/$PROJECT_ID/[IMAGE_NAME]:latest\"]\n }\n\n where \\[IMAGE_NAME\\] is the name of your image.\n2. Build your image using the above build config:\n\n gcloud builds submit --config cloudbuild.json .\n\nCaching directories with Google Cloud Storage\n---------------------------------------------\n\nTo increase the speed of a build, reuse the results from a previous build. You\ncan copy the results of a previous build to a Google Cloud Storage bucket, use\nthe results for faster calculation, and then copy the new results back to the\nbucket. Use this method when your build takes a long time and produces a small\nnumber of files that does not take time to copy to and from Google Cloud\nStorage.\n\nUnlike `--cache-from`, which is only for Docker builds, Google Cloud Storage\ncaching can be used for\n[any builder supported by Cloud Build](https://github.com/GoogleCloudPlatform/cloud-builders).\n\nUse the following steps to cache directories using Google Cloud Storage: \n\n### YAML\n\n1. In your build config file, add instructions to:\n\n - Copy the results of a previous build from the Google Cloud Storage bucket.\n - Use the results for the current build.\n - Copy the new results back into the bucket.\n\n steps:\n - name: gcr.io/cloud-builders/gsutil\n args: ['cp', 'gs://mybucket/results.zip', 'previous_results.zip']\n # operations that use previous_results.zip and produce new_results.zip\n - name: gcr.io/cloud-builders/gsutil\n args: ['cp', 'new_results.zip', 'gs://mybucket/results.zip']\n\n2. Build your code using the above build config:\n\n gcloud builds submit --config cloudbuild.yaml .\n\n### JSON\n\n1. In your build config file, add instructions to:\n\n - Copy the results of a previous build from the Google Cloud Storage bucket.\n - Use the results for the current build.\n - Copy the new results back into the bucket.\n\n {\n \"steps\": [\n {\n \"name\": \"gcr.io/cloud-builders/gsutil\",\n \"args\": [\"cp\", \"gs://mybucket/results.zip\", \"previous_results.zip\"]\n },\n {\n // operations that use previous_results.zip and produce new_results.zip\n },\n {\n \"name\": \"gcr.io/cloud-builders/gsutil\",\n \"args\": [\"cp\", \"new_results.zip\", \"gs://mybucket/results.zip\"]\n }\n ]\n }\n\n2. Build your code using the above build config:\n\n gcloud builds submit --config cloudbuild.json .\n\nAvoiding the upload of unnecessary files\n----------------------------------------\n\nWhen a build is triggered, your code directory is uploaded for use by\nCloud Build.\n\nYou can exclude files not needed by your build with a\n[`.gcloudignore`](/sdk/gcloud/reference/topic/gcloudignore)\nfile to optimize the upload time.\n\nExamples of commonly excluded files include:\n\n- Documentation and sample code for project developers\n- Generated scaffolding code, binaries, `*.jar` files, or compiled web assets used for development.\n- Vendored, third-party dependencies for local development\n\nTo prepare a `.gcloudignore` file to address these cases, create a file in your\nproject root with contents such as: \n\n .git\n dist\n node_modules\n vendor\n *.jar\n\nExcluding compiled code and third-party dependencies also results in a more\nconsistent build process and a reduced risk of accidental deployment of code\nthat is still under active development.\n\nWhat's next\n-----------\n\n- Learn how to [increase vCPU for builds](/build/docs/optimize-builds/increase-vcpu-for-builds)."]]