GitHub Actions Advanced Workflow로 구축하는 완전 자동화 CI/CD Pipeline
GitHub Actions 고급 워크플로우를 활용하여 Docker, Kubernetes 환경에서 완전 자동화된 CI/CD 파이프라인을 구축하는 실전 가이드입니다.
GitHub Actions Advanced Workflow로 구축하는 완전 자동화 CI/CD Pipeline
현대 소프트웨어 개발에서 CI/CD는 더 이상 선택이 아닌 필수입니다. GitHub Actions는 강력한 자동화 플랫폼으로, 단순한 테스트 실행을 넘어 복잡한 멀티 스테이지 배포까지 처리할 수 있습니다. 이 글에서는 Docker 컨테이너화와 Kubernetes 배포를 포함한 고급 워크플로우 구축 방법을 상세히 알아보겠습니다.
GitHub Actions 고급 워크플로우 아키텍처 설계
효율적인 CI/CD 파이프라인을 구축하기 위해서는 먼저 전체 아키텍처를 설계해야 합니다. 일반적인 고급 워크플로우는 다음과 같은 단계로 구성됩니다:
- 코드 품질 검증 (Linting, Testing)
- 보안 스캔 (Vulnerability Scanning)
- Docker 이미지 빌드 및 레지스트리 푸시
- 스테이징 환경 배포
- 통합 테스트 실행
- 프로덕션 환경 배포
이러한 단계들을 병렬로 실행하거나 조건부로 실행할 수 있도록 설계하는 것이 중요합니다.
멀티 스테이지 Docker 빌드 최적화
Docker 이미지 빌드는 CI/CD 파이프라인에서 가장 시간이 오래 걸리는 작업 중 하나입니다. 다음은 최적화된 멀티 스테이지 빌드 워크플로우입니다:
name: Advanced CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-test:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix={{branch}}-
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
Matrix Strategy를 활용한 병렬 테스트
복잡한 애플리케이션은 다양한 환경에서 테스트되어야 합니다. Matrix Strategy를 사용하면 여러 환경에서 동시에 테스트를 실행할 수 있습니다:
test-matrix:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 21]
include:
- os: ubuntu-latest
node-version: 20
coverage: true
steps:
- uses: actions/checkout@v4
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Generate coverage report
if: matrix.coverage
run: npm run test:coverage
- name: Upload coverage to Codecov
if: matrix.coverage
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
보안 스캔 및 취약점 검사 자동화
보안은 CI/CD 파이프라인에서 빠져서는 안 될 요소입니다. 다음은 종합적인 보안 스캔 워크플로우입니다:
security-scan:
runs-on: ubuntu-latest
needs: build-and-test
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: 'trivy-results.sarif'
- name: Run Snyk security scan
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --severity-threshold=high
Kubernetes 배포 자동화
Kubernetes 클러스터로의 자동 배포는 고급 워크플로우의 핵심입니다. 다음은 Helm을 사용한 배포 자동화 예시입니다:
deploy-staging:
runs-on: ubuntu-latest
needs: [build-and-test, security-scan]
if: github.ref == 'refs/heads/develop'
environment: staging
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Configure kubectl
uses: azure/k8s-set-context@v3
with:
method: kubeconfig
kubeconfig: ${{ secrets.KUBE_CONFIG_STAGING }}
- name: Setup Helm
uses: azure/setup-helm@v3
with:
version: '3.12.0'
- name: Deploy to staging
run: |
helm upgrade --install myapp ./helm-chart \
--namespace staging \
--create-namespace \
--set image.repository=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} \
--set image.tag=${{ github.sha }} \
--set environment=staging \
--wait --timeout=10m
- name: Run health checks
run: |
kubectl wait --for=condition=ready pod \
-l app=myapp \
-n staging \
--timeout=300s
kubectl get pods -n staging
환경별 배포 전략과 승인 프로세스
프로덕션 배포는 신중해야 합니다. GitHub Environments와 Protection Rules를 활용한 승인 프로세스를 구현할 수 있습니다:
deploy-production:
runs-on: ubuntu-latest
needs: deploy-staging
if: github.ref == 'refs/heads/main'
environment: production
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Configure kubectl
uses: azure/k8s-set-context@v3
with:
method: kubeconfig
kubeconfig: ${{ secrets.KUBE_CONFIG_PROD }}
- name: Blue-Green Deployment
run: |
# Current active deployment 확인
CURRENT_COLOR=$(kubectl get service myapp-service -o jsonpath='{.spec.selector.version}' || echo "blue")
NEW_COLOR=$([ "$CURRENT_COLOR" = "blue" ] && echo "green" || echo "blue")
echo "Deploying to $NEW_COLOR environment"
# New version 배포
helm upgrade --install myapp-$NEW_COLOR ./helm-chart \
--namespace production \
--set image.tag=${{ github.sha }} \
--set version=$NEW_COLOR \
--wait --timeout=15m
# Health check
kubectl wait --for=condition=ready pod \
-l app=myapp,version=$NEW_COLOR \
-n production \
--timeout=300s
# Traffic switch
kubectl patch service myapp-service \
-p '{"spec":{"selector":{"version":"'$NEW_COLOR'"}}}'
echo "Successfully deployed to production using $NEW_COLOR"
고급 워크플로우 모니터링 및 알림
배포 후 모니터링과 알림 시스템은 운영 안정성을 보장합니다:
notify-deployment:
runs-on: ubuntu-latest
needs: [deploy-production]
if: always()
steps:
- name: Notify Slack on success
if: needs.deploy-production.result == 'success'
uses: 8398a7/action-slack@v3
with:
status: success
channel: '#deployments'
text: |
🚀 Production deployment successful!
Repository: ${{ github.repository }}
Commit: ${{ github.sha }}
Author: ${{ github.actor }}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
- name: Notify on failure
if: needs.deploy-production.result == 'failure'
uses: 8398a7/action-slack@v3
with:
status: failure
channel: '#alerts'
text: |
❌ Production deployment failed!
Repository: ${{ github.repository }}
Commit: ${{ github.sha }}
Please check the logs immediately.
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
성능 최적화와 비용 관리
GitHub Actions 사용 시간을 최적화하고 비용을 절약하기 위한 전략들입니다:
optimize-workflow:
runs-on: ubuntu-latest
steps:
- name: Cache dependencies
uses: actions/cache@v4
with:
path: |
~/.npm
~/.cache/pip
~/.cargo
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json', '**/requirements.txt', '**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-deps-
- name: Use self-hosted runners for heavy tasks
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: [self-hosted, linux, x64, gpu]
마무리
GitHub Actions의 고급 워크플로우를 통해 Docker 컨테이너화부터 Kubernetes 배포까지 완전 자동화된 CI/CD 파이프라인을 구축할 수 있습니다. 보안 스캔, 병렬 테스트, 환경별 배포 전략을 적절히 조합하면 안정적이고 효율적인 개발 프로세스를 만들 수 있습니다. 지속적인 모니터링과 최적화를 통해 팀의 생산성을 크게 향상시킬 수 있을 것입니다.
관련 게시글
GitOps Workflow Design: Kubernetes CI/CD 자동화 가이드
GitOps 원칙을 기반으로 Kubernetes 환경에서 CI/CD 파이프라인을 설계하고 자동화하는 방법을 상세히 안내합니다. Docker, Argo CD, Helm을 활용한 효율적인 인프라 관리 전략을 다룹니다.
ArgoCD를 활용한 Kubernetes Continuous Delivery 심층 가이드
ArgoCD를 이용한 Kubernetes 환경에서의 GitOps 기반 지속적 배포(Continuous Delivery) 전략을 심층적으로 다룹니다. 설치부터 Application 관리, 고급 기능 및 DevOps 베스트 프랙티스까지, 자동화된 인프라 배포를 위한 가이드입니다.
Kubernetes Pod Service Deployment 심층 가이드
Kubernetes의 핵심 구성 요소인 Pod, Service, Deployment를 DevOps 관점에서 심층 분석하고, 실제 예시와 CLI 명령어를 통해 컨테이너 오케스트레이션의 기본기를 다집니다.