create #183
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: Deploy to EC2 | |
| on: | |
| push: | |
| branches: | |
| - develop | |
| - main | |
| env: | |
| # 현재 푸시된 브랜치를 가져옵니다 (develop 또는 main) | |
| GIT_BRANCH: ${{ github.ref_name }} | |
| # 브랜치별로 다른 EC2 접속 정보를 주입합니다. | |
| # → secrets.EC2_HOST_DEV, EC2_USER_DEV, EC2_KEY_DEV 는 develop용 | |
| # → secrets.EC2_HOST_PROD, EC2_USER_PROD, EC2_KEY_PROD 는 main용 | |
| EC2_HOST: ${{ github.ref == 'refs/heads/develop' && secrets.DEV_EC2_HOST || secrets.PROD_EC2_HOST }} | |
| EC2_USER: ${{ github.ref == 'refs/heads/develop' && secrets.DEV_EC2_USER || secrets.PROD_EC2_USER }} | |
| EC2_KEY: ${{ github.ref == 'refs/heads/develop' && secrets.DEV_EC2_KEY || secrets.PROD_EC2_KEY }} | |
| # 브랜치별 Spring 프로파일 설정 | |
| SPRING_PROFILES: ${{ github.ref == 'refs/heads/develop' && 'dev,cloud' || 'prod,cloud' }} | |
| jobs: | |
| deploy: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Checkout source code | |
| uses: actions/checkout@v3 | |
| - name: Generate Docker image tag from Git commit | |
| id: vars | |
| run: echo "TAG=$(git rev-parse --short HEAD)" >> $GITHUB_ENV | |
| - name: Deploy via SSH | |
| uses: appleboy/[email protected] | |
| with: | |
| host: ${{ env.EC2_HOST }} | |
| username: ${{ env.EC2_USER }} | |
| key: ${{ env.EC2_KEY }} | |
| script: | | |
| set -e | |
| echo "[1] 이동: 프로젝트 디렉토리로" | |
| cd /home/ec2-user/onRank/onRank-spring | |
| echo "[2] Git 최신화" | |
| git pull origin ${{ env.GIT_BRANCH }} | |
| echo "[3] 기존 Docker 컨테이너 정리" | |
| docker stop onrank-api || true | |
| docker rm onrank-api || true | |
| echo "[4] Gradle 빌드" | |
| ./gradlew clean build -x test || { cat build/libs/*.log; exit 1; } | |
| echo "[5] Docker 이미지 빌드 (태그: ${{ env.TAG }})" | |
| docker build -t onrank-api:${{ env.TAG }} . | |
| echo "[6] Docker 컨테이너 실행" | |
| docker run -d \ | |
| --name onrank-api \ | |
| --restart unless-stopped \ | |
| -e SPRING_PROFILES_ACTIVE="${{ env.SPRING_PROFILES }}" \ | |
| -p 8080:8080 \ | |
| -p 8081:8081 \ | |
| onrank-api:${{ env.TAG }} | |
| echo "[7] Waiting for container to report healthy status..." | |
| sleep 30 | |
| for i in {1..20}; do | |
| HEALTH=$(docker inspect --format='{{.State.Health.Status}}' onrank-api) | |
| echo " → Attempt $i: status=$HEALTH" | |
| if [ "$HEALTH" = "healthy" ]; then | |
| echo "✅ Container is healthy!" | |
| break | |
| elif [ "$HEALTH" = "unhealthy" ]; then | |
| echo "❌ Container is unhealthy! Dumping logs:" | |
| docker logs onrank-api | |
| exit 1 | |
| fi | |
| sleep 5 | |
| done | |
| # 20회 시도 후에도 healthy 상태가 아니면 에러로 처리 | |
| if [ "$HEALTH" != "healthy" ]; then | |
| echo "❌ Container did not become healthy after 20 attempts; last status=$HEALTH" | |
| docker logs onrank-api | |
| exit 1 | |
| fi |