콘텐츠로 이동

GitHub Actions CI Workflow: Build Cache와 Image Build

Interactive Diagram

새 탭 ↗

Application Build process 최적화 및 성능 개선을 위한 방식은 다음과 같다.

  • GitHub Actions 기반 caching
  • Self-Hosted Runner의 Persistent Volume 기반 caching
  • Container Registry Image 기반 caching

이번 프로젝트에서는 CI Pipeline의 container image build process를 한 가지 방식으로 일원화하여 Backend/Frontend에 모두 동일한 방식을 적용하고자 했다. Public GitHub Actions에서 제공하는 caching은 resource limit으로 인해 고려하지 않았고, Self-Hosted Runner 관리도 최소한으로 유지하기 위해 Volume을 별도로 사용하지 않았다. 이런 이유로 Container Registry Image 기반 caching 방식을 적용했다.

Container Image의 cache layer를 Container Registry에 저장하고, 해당 cache 기반으로 빌드 시간을 단축하고 최적화한다. Registry Cache는 Container Registry에 저장되며, 여러 빌드에서 재사용 가능하다.

ACR(Azure Container Registries) 기반 Image Cache 관리 예시로, github action workflow에서 docker buildx 기반(내부적으로 buildkit 활용)으로 build한다.

- name: Build and push Container image
uses: docker/build-push-action@v6.5.0
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
with:
context: .
file: ./Dockerfile
push: true
cache-from: type=registry,ref=${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-cache
cache-to: type=registry,ref=${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-cache,mode=max
tags: |
${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-${{ inputs.environment }}:${{ env.IMAGE_TAG }}
${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-${{ inputs.environment }}:latest
  • context: Build 컨텍스트(현재 디렉토리 .)
  • file: 사용할 Dockerfile 경로
  • push: 빌드된 이미지를 Container Registry에 푸시할지 여부
  • cache-from: Container Registry에서 이전에 저장된 cache를 사용 (type=registry로 지정)
  • cache-to: Container Registry에 새로운 cache를 저장 (mode=max로 가능한 많은 cache 데이터 저장)
  • tags: IMAGE_TAG 및 latest 태그 적용

전체 GitHub Actions Workflow 예시:

jobs:
ci:
name: (${{ inputs.environment }}) Push Container image and Update K8s Manifests
runs-on: "${{ inputs.runner }}"
steps:
- name: Check out the repo
uses: actions/checkout@v4.1.7
with:
token: ${{ secrets.GH_ADMIN_TOKEN }}
fetch-depth: 1
- name: Get image tag
run: echo "IMAGE_TAG=$(TZ=Asia/Seoul date +%Y%m%d%H%M%S)" >> $GITHUB_ENV
- name: Log in to Azure CLI
env:
AZURE_CREDENTIALS: ${{ secrets.AZURE_CREDENTIALS_COMMON }}
run: |
echo "$AZURE_CREDENTIALS" > azure_credentials.json
az login \
--service-principal \
--username $(jq -r .clientId azure_credentials.json) \
-p=$(jq -r .clientSecret azure_credentials.json) \
--tenant $(jq -r .tenantId azure_credentials.json)
az account set --subscription $(jq -r .subscriptionId azure_credentials.json)
- name: Login to ACR Private
run: |
az acr login --name ${{ vars.ACR_NAME }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.6.1
- name: Build and push Container image
uses: docker/build-push-action@v6.5.0
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
with:
context: .
file: ./Dockerfile
push: true
cache-from: type=registry,ref=${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-cache
cache-to: type=registry,ref=${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-cache,mode=max
tags: |
${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-${{ inputs.environment }}:${{ env.IMAGE_TAG }}
${{ vars.ACR_LOGIN_SERVER }}/${{ vars.ACR_REPOSITORY }}-${{ inputs.environment }}:latest

CI/CD Pipeline의 설계 고려사항으로는, GitHub hosted runner 및 self-hosted runner 모두에서 동작 가능하도록 설계했고, CI Pipeline은 개발 Language/Framework와 연관되어 작업 step이 달라질 수 있으므로 Application별로 각각 관리했다. CD Job은 GitOps Manifests 관리를 위한 Repository 기반으로 실행되며, Argo CD가 설치된 k8s cluster와 통신 가능해야 한다.

CI/CD Workflow Diagram

CD Workflow는 Custom Actions 기반으로 공통 활용 가능하도록 구성했으며, Backend/Frontend 관계없이 k8s cluster에 Argo CD Application 형태로 배포되므로 flow가 모두 동일하다.

CD Job 상세 Workflow

Application CI/CD Pipeline 설계 내역이 반영된 GitHub Actions Workflow를 정의한 Script를 살펴본다.

  • Build Container Image and Push
  • Application 특성 별로 달라질 것을 고려하여, 각 application repository의 workflow로 setup

주요 Step은 GitOps 리포지토리 체크아웃 → Tag/Branch 환경변수 구성 → NodeJS 설치 및 npm install → Lint 수행 → ACR Login → Docker Buildx 설치 → Docker Build & Push → Git Tag 설정 → CD Action 호출 순서다.

- name: Check out the repo
uses: actions/checkout@v4
- name: Set Tag for Build and Artifacts
run: |
echo "IMAGE_TAG=$(TZ=UTC-9 date +'%y%m%d.%H%M').$(printf 'v%03d' ${{github.run_number}})" >> $GITHUB_ENV
- name: Extract branch name
shell: bash
run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
id: extract_branch
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20.14
- name: Install Node.js dependencies
run: npm install
- name: Run linters
run: npm run lint ## Lint 수행
- name: ACR login
uses: azure/docker-login@v1
with:
login-server: ${{ secrets.ACR_LOGIN_SERVER }}
username: ${{ secrets.ACR_USERNAME }}
password: ${{ secrets.ACR_PASSWORD }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.6.1
- name: Build and push Container image
uses: docker/build-push-action@v6.5.0
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
with:
context: .
file: ./Dockerfile
push: true
cache-from: type=registry,ref=${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-cache
cache-to: type=registry,ref=${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-cache,mode=max
tags: |
${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-${{ steps.extract_branch.outputs.branch }}:${{ env.IMAGE_TAG }}
${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-${{ steps.extract_branch.outputs.branch }}:latest
- name: Add Git tag to source repository and setup output"
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
REPO_TAG: ${{ steps.extract_branch.outputs.branch }}.${{ github.event.repository.name }}.${{ env.IMAGE_TAG }}
run: |
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git config --global user.name "${{ github.actor }}"
git tag -a "${{ env.REPO_TAG }}" -m "Push tag ${{ env.REPO_TAG }}"
git push origin "${{ env.REPO_TAG }}"
echo "image_tag=$(echo ${{ env.IMAGE_TAG }})" >> $GITHUB_OUTPUT
echo "repo_tag=$(echo ${{ env.REPO_TAG }})" >> $GITHUB_OUTPUT
id: set_tag
- name: Run CD actions
uses: example-org/platform-argocd-apps/.github/actions/cd@develop
with:
gitops_repo_name: ${{ vars.GITOPS_REPO_NAME }}
gitops_token: ${{ secrets.GITOPS_TOKEN }}
branch: ${{ needs.ci.outputs.branch }}
argocd_server: ${{ vars.ARGOCD_SERVER }}
argocd_admin_user: ${{ secrets.ARGOCD_ADMIN_USER }}
argocd_admin_pass: ${{ secrets.ARGOCD_ADMIN_PASS }}
argocd_app_name: ${{ github.event.repository.name }}
acr_login_server: ${{ secrets.ACR_LOGIN_SERVER }}
image_tag: ${{ needs.ci.outputs.image_tag }}
repo_tag: ${{ needs.ci.outputs.repo_tag }}

전체 Pipeline Manifest:

name: Build and Deploy
on:
workflow_dispatch:
## GitHub Action 탭 내에서 수동 트리거
jobs:
ci:
name: Build and push container image
runs-on: ubuntu-latest ## github managed runner
# runs-on: arc-runner-platform ## self-hosted runner
outputs:
branch: ${{ steps.extract_branch.outputs.branch }}
image_tag: ${{ steps.set_tag.outputs.image_tag }}
repo_tag: ${{ steps.set_tag.outputs.repo_tag }}
steps:
- name: Check out the repo
uses: actions/checkout@v4 ## actions/checkout action을 통해 source checkout
# Tagging rule
# [yy].[m].[d].[H][M].v[actions build number]
- name: Set Tag for Build and Artifacts ## Docker Image 에 설정할 Tag 구성
run: |
echo "IMAGE_TAG=$(TZ=UTC-9 date +'%y%m%d.%H%M').$(printf 'v%03d' ${{github.run_number}})" >> $GITHUB_ENV
- name: Extract branch name
shell: bash
run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
id: extract_branch
- name: Set up Node.js
uses: actions/setup-node@v4 ## Pipeline 내 테스트 설정을 위하여 actions/setup-node Action을 통해 Node 구성
with:
node-version: 20.14
- name: Install Node.js dependencies
run: npm install
- name: Run linters
run: npm run lint ## Lint 수행
- name: ACR login
uses: azure/docker-login@v1 ## docker image pull/push를 위하여 azure/dokcer-login action을 통해 ACR에 login
with:
login-server: ${{ secrets.ACR_LOGIN_SERVER }}
username: ${{ secrets.ACR_USERNAME }}
password: ${{ secrets.ACR_PASSWORD }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.6.1 ## docker/setup-uildx-action action을 통해 docker build/push 를 할 수 있는 환경 구성
- name: Build and push Container image
uses: docker/build-push-action@v6.5.0
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
with:
context: .
file: ./Dockerfile
push: true
cache-from: type=registry,ref=${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-cache
cache-to: type=registry,ref=${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-cache,mode=max
tags: |
${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-${{ steps.extract_branch.outputs.branch }}:${{ env.IMAGE_TAG }}
${{ secrets.ACR_LOGIN_SERVER }}/${{ github.event.repository.name }}-${{ steps.extract_branch.outputs.branch }}:latest
## extract_branch step에서 구성한 태그로 docker image tagging 후 Login된 ACR에 image push
- name: Add Git tag to source repository and setup output"
env:
IMAGE_TAG: ${{ env.IMAGE_TAG }}
REPO_TAG: ${{ steps.extract_branch.outputs.branch }}.${{ github.event.repository.name }}.${{ env.IMAGE_TAG }}
run: |
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git config --global user.name "${{ github.actor }}"
git tag -a "${{ env.REPO_TAG }}" -m "Push tag ${{ env.REPO_TAG }}"
git push origin "${{ env.REPO_TAG }}"
echo "image_tag=$(echo ${{ env.IMAGE_TAG }})" >> $GITHUB_OUTPUT
echo "repo_tag=$(echo ${{ env.REPO_TAG }})" >> $GITHUB_OUTPUT
id: set_tag
## (branch_name).(service_name).(Docker Tag) 형태로 git commit tag 설정
cd:
name: Update manifests and sync argocd app ## ci job에서 push 된 docker image를 Argo CD를 통해 배포하는 job
needs: ci
# runs-on: ubuntu-latest
runs-on: arc-runner-platform ## self-hosted runner를 통해 Argo CD 배포 진행
steps:
- name: Run CD actions
uses: example-org/platform-argocd-apps/.github/actions/cd@develop
with:
gitops_repo_name: ${{ vars.GITOPS_REPO_NAME }}
gitops_token: ${{ secrets.GITOPS_TOKEN }}
branch: ${{ needs.ci.outputs.branch }}
argocd_server: ${{ vars.ARGOCD_SERVER }}
argocd_admin_user: ${{ secrets.ARGOCD_ADMIN_USER }}
argocd_admin_pass: ${{ secrets.ARGOCD_ADMIN_PASS }}
argocd_app_name: ${{ github.event.repository.name }}
acr_login_server: ${{ secrets.ACR_LOGIN_SERVER }}
image_tag: ${{ needs.ci.outputs.image_tag }}
repo_tag: ${{ needs.ci.outputs.repo_tag }}

example-org/platform-argocd-apps/.github/actions/cd@develop GitHub Action을 활용하여 GitOps manifests를 업데이트하고 Argo CD 애플리케이션을 동기화한다.

Input필수 여부기본값설명
gitops_repo_name✅""GitOps manifests가 저장된 리포지토리 이름
gitops_token✅""GitOps 리포지토리에 접근하기 위한 GitHub Token
branch✅""GitOps manifests를 업데이트할 브랜치
argocd_repo✅https://github.com/example-org/platform-argocd-apps.gitArgo CD GitOps manifests 리포지토리
argocd_dest_server✅https://kubernetes.default.svcArgo CD가 배포할 대상 Kubernetes 클러스터
argocd_server✅""Argo CD 서버 주소
argocd_admin_user✅""Argo CD 관리자 계정
argocd_admin_pass✅""Argo CD 관리자 비밀번호
argocd_app_name✅""Argo CD 애플리케이션 이름
acr_login_server❌""ACR(Azure Container Registry) 로그인 서버
image_tag❌""배포할 컨테이너 이미지 태그
repo_tag❌""Git 태그

주요 Step은 GitOps 리포지토리 체크아웃 → Kustomize 설치 → 브랜치 기준 배포 경로(dev/prd) 설정 → 이미지 태그 반영 → Manifest 저장소에 Git Tag push → Argo CD CLI 설치/로그인 → Application 설정 → Sync → repo_tag 옵션 갱신 순서다.

- name: Checkout GitOps manifests repository
uses: actions/checkout@v4.2.2
with:
repository: ${{ github.repository_owner }}/${{ inputs.gitops_repo_name }}
token: ${{ inputs.gitops_token }}
- name: Setup kustomize
uses: imranismail/setup-kustomize@v2
- name: Set gitops directory path based on branch
run: |
if [[ "${{ inputs.branch }}" == "main" ]]; then
echo "GITOPS_PATH=prd" >> $GITHUB_ENV
elif [[ "${{ inputs.branch }}" == "develop" ]]; then
echo "GITOPS_PATH=dev" >> $GITHUB_ENV
fi
shell: bash
- name: Update Kubernetes Resources with New Docker Image Tag
run: |
cd ${{ inputs.argocd_app_name }}/overlays/${{ env.GITOPS_PATH }}
if [[ -n "${{ inputs.image_tag }}" ]]; then
kustomize edit set image \
${{ inputs.argocd_app_name }}=${{ inputs.acr_login_server }}/${{ inputs.argocd_app_name }}-${{ inputs.branch }}:${{ inputs.image_tag }}
kustomize build .
fi
shell: bash
- name: Add Git Tag to Manifest Repository
run: |
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git config --global user.name "${{ github.actor }}"
if [[ -n "${{ inputs.image_tag }}" ]]; then
git add .
git commit --allow-empty -m 'update version tag ${{ inputs.repo_tag }} from GitHub Action'
git push origin ${{ inputs.branch }} -f
git tag -af "${{ inputs.repo_tag }}" -m "Update ${{ inputs.repo_tag }}"
git push origin "${{ inputs.repo_tag }}" -f
fi
shell: bash
- name: Set-up Argo CD CLI
run: |
curl -sSL -o argocd-linux-amd64 https://github.com/argoproj/argo-cd/releases/latest/download/argocd-linux-amd64
sudo install -m 555 argocd-linux-amd64 /usr/local/bin/argocd
rm argocd-linux-amd64
argocd login --grpc-web --insecure --plaintext ${{ inputs.argocd_server }} \
--username ${{ inputs.argocd_admin_user }} \
--password ${{ inputs.argocd_admin_pass }}
shell: bash
- name: Set Argo CD Application
run: |
argocd app set ${{ inputs.argocd_app_name }} \
--path ${{ inputs.argocd_app_name }}/overlays/${{ env.GITOPS_PATH }} \
--repo ${{ inputs.argocd_repo }} \
--dest-server ${{ inputs.argocd_dest_server }} \
--revision ${{ inputs.repo_tag }} \
--sync-option Prune=true
shell: bash
- name: Sync Argo CD Application
run: |
argocd app sync --prune \
${{ inputs.argocd_app_name }}
shell: bash
- name: Update repo_tag options in workflow_dispatch
run: |
WORKFLOW_FILE=".github/workflows/argocd.yml"
git fetch --tags
TAGS=$(git tag --sort=-v:refname | head -20)
echo "Latest Tags: $TAGS"
TAGS_YAML=$(echo "$TAGS" | sed 's/^/ - /')
yq eval -i '
.on.workflow_dispatch.inputs.repo_tag.options = ["=== select ==="] + (env(TAGS_YAML))
' "$WORKFLOW_FILE"
git add "$WORKFLOW_FILE"
git commit --allow-empty -m "Update repo_tag options with latest tags"
git push
shell: bash

전체 Custom Action manifest(example-org/platform-argocd-apps/.github/actions/cd@develop):

name: CD with argocd
description: Update gitops manifests and sync argocd app
inputs:
gitops_repo_name:
required: true
default: ""
gitops_token:
required: true
default: ""
branch:
required: true
default: ""
argocd_repo:
required: true
default: "https://github.com/example-org/platform-argocd-apps.git"
argocd_dest_server:
required: true
default: "https://kubernetes.default.svc"
argocd_server:
required: true
default: ""
argocd_admin_user:
required: true
default: ""
argocd_admin_pass:
required: true
default: ""
argocd_app_name:
required: true
default: ""
acr_login_server:
required: false
deafult: ""
image_tag:
required: false
default: ""
repo_tag:
required: false
default: ""
runs:
using: "composite" ## 외부에서 액션을 사용할 수 있도록 여러 Step을 묶어서 하나의 Action 으로 정의
steps:
- name: Checkout GitOps manifests repository
uses: actions/checkout@v4.2.2
with:
repository: ${{ github.repository_owner }}/${{ inputs.gitops_repo_name }}
token: ${{ inputs.gitops_token }}
- name: Setup kustomize
uses: imranismail/setup-kustomize@v2
- name: Set gitops directory path based on branch
run: |
if [[ "${{ inputs.branch }}" == "main" ]]; then
echo "Setting path to prd"
echo "GITOPS_PATH=prd" >> $GITHUB_ENV
elif [[ "${{ inputs.branch }}" == "develop" ]]; then
echo "Setting path to dev"
echo "GITOPS_PATH=dev" >> $GITHUB_ENV
else
echo "Setting default path"
fi
shell: bash
- name: Update Kubernetes Resources with New Docker Image Tag
env:
GITOPS_PATH: ${{ env.GITOPS_PATH }}
run: |
cd ${{ inputs.argocd_app_name }}/overlays/${{ env.GITOPS_PATH }}
if [[ -n "${{ inputs.image_tag }}" ]]; then
kustomize edit set image \
${{ inputs.argocd_app_name }}=${{ inputs.acr_login_server }}/${{ inputs.argocd_app_name }}-${{ inputs.branch }}:${{ inputs.image_tag }}
kustomize build .
else
echo "Skipping image update as image_tag is empty."
fi
shell: bash
- name: Add Git Tag to Manifest Repository "${{ inputs.repo_tag }}"
run: |
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git config --global user.name "${{ github.actor }}"
if [[ -n "${{ inputs.image_tag }}" ]]; then
git add .
git commit --allow-empty -m 'update version tag ${{ inputs.repo_tag }} from GitHub Action'
git push origin ${{ inputs.branch }} -f
git tag -af "${{ inputs.repo_tag }}" -m "Update ${{ inputs.repo_tag }}"
git push origin "${{ inputs.repo_tag }}" -f
else
echo "Skipping repository commit push and tag. (without build process)"
fi
shell: bash
- name: Set-up Argo CD CLI
run: |
curl -sSL -o argocd-linux-amd64 https://github.com/argoproj/argo-cd/releases/latest/download/argocd-linux-amd64
sudo install -m 555 argocd-linux-amd64 /usr/local/bin/argocd
rm argocd-linux-amd64
argocd login --grpc-web --insecure --plaintext ${{ inputs.argocd_server }} \
--username ${{ inputs.argocd_admin_user }} \
--password ${{ inputs.argocd_admin_pass }}
shell: bash
- name: Set Argo CD Application
env:
GITOPS_PATH: ${{ env.GITOPS_PATH }}
run: |
argocd app set ${{ inputs.argocd_app_name }} \
--path ${{ inputs.argocd_app_name }}/overlays/${{ env.GITOPS_PATH }} \
--repo ${{ inputs.argocd_repo }} \
--dest-server ${{ inputs.argocd_dest_server }} \
--revision ${{ inputs.repo_tag }} \
--sync-option Prune=true
shell: bash
- name: Sync Argo CD Application
run: |
argocd app sync --prune \
${{ inputs.argocd_app_name }}
shell: bash
- name: Update repo_tag options in workflow_dispatch
run: |
WORKFLOW_FILE=".github/workflows/argocd.yml"
# yq install
if ! command -v yq &> /dev/null; then
curl -sSL -o yq_linux_amd64 https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64
sudo install -m 555 yq_linux_amd64 /usr/local/bin/yq
rm yq_linux_amd64
fi
# Get latest tags
git fetch --tags
TAGS=$(git tag --sort=-v:refname | head -20)
echo "Latest Tags: $TAGS_ARRAY"
# Update inputs.repo_tag options
TAGS_YAML=$(echo "$TAGS" | sed 's/^/ - /') yq eval -i '
.on.workflow_dispatch.inputs.repo_tag.options = ["=== select ==="] + (env(TAGS_YAML))
' "$WORKFLOW_FILE"
# 변경사항 Git에 커밋 & 푸시
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git config --global user.name "${{ github.actor }}"
git add "$WORKFLOW_FILE"
git commit --allow-empty -m "Update repo_tag options with latest tags"
git push
shell: bash

GitOps CD Workflow: Image Signing과 Smoke Test에서 이어서 본다.