CD with Docker #160
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name: CD with Docker | |
| on: | |
| workflow_run: | |
| workflows: [ "Java CI & Docker Build" ] # CI 워크플로우 name과 정확히 일치 | |
| types: [ completed ] | |
| branches: [ "dev" ] | |
| permissions: | |
| contents: read | |
| packages: read | |
| jobs: | |
| deploy: | |
| if: ${{ github.event.workflow_run.conclusion == 'success' }} | |
| runs-on: [self-hosted, new-ec2] | |
| env: | |
| CONTAINER_NAME: ${{ vars.CONTAINER_NAME }} | |
| NETWORK_NAME: ${{ vars.NETWORK_NAME }} | |
| DEV_WEB_PORT: ${{ vars.DEV_WEB_PORT }} | |
| FULL_SHA: ${{ github.event.workflow_run.head_sha }} | |
| steps: | |
| # 1) GHCR 로그인 | |
| - name: Login to GHCR | |
| uses: docker/login-action@v3 | |
| with: | |
| registry: ghcr.io | |
| username: ${{ github.actor }} | |
| password: ${{ secrets.ACTION_TOKEN }} | |
| # 2) SHA 변수 설정 | |
| - name: Set SHORT_SHA | |
| run: | | |
| echo "SHORT_SHA=${FULL_SHA:0:7}" >> $GITHUB_ENV | |
| # 3) 네트워크가 없으면 생성 | |
| - name: Ensure Docker network exists | |
| run: | | |
| docker network inspect $NETWORK_NAME >/dev/null 2>&1 \ | |
| || docker network create $NETWORK_NAME | |
| # 4) 이미지 Pull | |
| - name: Pull Docker image | |
| run: | | |
| IMAGE=ghcr.io/lets-gu/backend:sha-${SHORT_SHA} | |
| echo "Pulling $IMAGE" | |
| docker pull "$IMAGE" | |
| # 5) 기존 컨테이너 제거 | |
| - name: Remove old container | |
| run: docker rm -f "$CONTAINER_NAME" || true | |
| # 6) 오래된 이미지 정리 | |
| - name: Prune old images | |
| run: | | |
| docker images ghcr.io/lets-gu/backend \ | |
| --format '{{.Repository}}:{{.Tag}}' \ | |
| | grep -v "sha-${SHORT_SHA}" \ | |
| | xargs -r docker rmi -f || true | |
| # 7) 새 컨테이너 실행 (dev 프로파일로 실행) | |
| - name: Run new container | |
| run: | | |
| IMAGE=ghcr.io/lets-gu/backend:sha-${SHORT_SHA} | |
| echo "Running $IMAGE with dev profile" | |
| docker run -d \ | |
| --name "$CONTAINER_NAME" \ | |
| --network "$NETWORK_NAME" \ | |
| -p "$DEV_WEB_PORT:8080" \ | |
| -e USE_PROFILE=dev \ | |
| -e TZ=Asia/Seoul \ | |
| "$IMAGE" |