방관 / github action을 이용한 docker build 와 private push & pull

Created Wed, 26 Jun 2024 00:00:00 +0000 Modified Wed, 26 Jun 2024 20:04:57 +0900

github action을 이용한 docker build 와 private push & pull

상황에 따라 다르겠지만, 초기/연습용 프로젝트의 경우 설계/개발보다 CI/CD 구성 과정이 비대해질 수 있으므로 직접 구성하는 것 보다 이미 기존에 구성되어 있는 서비스를 이용하는편이 효율적이다.

VCS(Version Control System)로 github를 사용하는 경우 무료로 제공되는 github action을 사용하면 이미 구성되어 있는 워크플로를 이용하면 비교적 구성이 편하다.

만약 무료 사용량을 초과 하거나 추가적인 설정이 필요할 경우 Self-hosted Runner를 이용할 수 있다.

해당 repo는 여러 back, front 와 배포를 이용한 repo가 나뉘어 있는 구성이며 self-hosted는 ubuntu를 이용한 내부 PC 였으나 build가 다수 발생하는 경우 문제가 발생할 수 있는 사양이므로 다음과 같이 구성되었다.

해당 소스에서 ${{ secrets.var }} 또는 ${{ env.var }}는 각 repo의 Settings - Actions secrets and variables에서 설정할 수 있다.

  • 이는 환경 변수(.env)등에 저장된 값은 공개되면 안되기 때문에 별도로 저장하기 때문이며 저장된 값을 이용해 설정 파일을 생성한다.

실제 소스 repo에서 특정 브랜치에 push되거나 사용자가 직접 실행하는 경우

  • ubuntu-latest을 이용하여 해당 repo checkout
  • Docker Registry를 이용한 private server 로그인
  • 현재 date를 이용하여 버전이 겹치지 않도록 설정 후 Build & Push
  • github cli를 이용하여 설정한 배포 repo에 특정 event 호출
name: dev push

on:
  push:
    branches: [dev]
  workflow_dispatch:
    
jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Login to Docker Registry
        run: |
          echo "${{ secrets.REGISTRY_PASS }}" | docker login ${{ secrets.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USER }} --password-stdin          

      - name: Docker Build and Push
        run: |
          current_time=$(date +"%Y%m%d%H%M%S")
          registry=${{ secrets.REGISTRY_TAG }}
          docker build -t $registry:$current_time -t $registry:latest .
          docker push $registry:$current_time
          docker push $registry:latest
          docker logout          

      - run: gh api /repos/${{ env.repo }}/dispatches -f event_type='deploy'
        env:
          GH_TOKEN: ${{ secrets.PAT }}
  • 배포 repo에서 특정 이벤트가 발생하거나 사용자가 직접 실행하는 경우
    • self-hosted를 이용하여 해당 repo checkout
    • Docker Registry를 이용한 private server 로그인
    • docker compose를 이용하여 pull 후 restart
name: Repository Dispatch

on:
  repository_dispatch:
    types: [ deploy ]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: self-hosted # ubuntu

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      
      - name: Login to Docker Registry
        run: |
          echo "${{ secrets.REGISTRY_PASS }}" | docker login ${{ secrets.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USER }} --password-stdin
                    
      - name: Docker Compose Up
        run: |
          docker compose pull
          docker compose up -d