Build, Push, and Deploy Docker Image to EC2 #22
Workflow file for this run
This file contains 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: Build, Push, and Deploy Docker Image to EC2 | |
on: | |
workflow_run: | |
workflows: ["Kotlin Lint Check"] # lint.yml이 끝난 후 실행dfd | |
types: | |
- completed | |
jobs: | |
build: | |
runs-on: ubuntu-latest | |
steps: | |
# 1. 코드 체크아웃 | |
- name: Checkout code | |
uses: actions/checkout@v3 | |
# 2. AWS 자격 증명 설정 | |
- name: Configure AWS credentials | |
uses: aws-actions/configure-aws-credentials@v3 | |
with: | |
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
aws-region: ap-northeast-2 | |
# 3. AWS ECR 로그인 | |
- name: Log in to Amazon ECR | |
uses: aws-actions/amazon-ecr-login@v1 | |
# 4. 도커 이미지 빌드 | |
- name: Build Docker image | |
run: | | |
docker build -t memo-with-tags-backend:latest . | |
# 5. 도커 이미지를 ECR로 푸시 | |
- name: Push Docker image to ECR | |
run: | | |
REPOSITORY_URI=739275468912.dkr.ecr.ap-northeast-2.amazonaws.com/memo-with-tags | |
TAG=$(echo $GITHUB_SHA | cut -c1-7) # 커밋 해시 앞 7자리로 태그 생성 | |
docker tag memo-with-tags-backend:latest $REPOSITORY_URI:$TAG | |
docker push $REPOSITORY_URI:$TAG | |
# 6. EC2 서버에서 Docker 이미지 실행 | |
- name: Deploy to EC2 | |
run: | | |
ssh -o StrictHostKeyChecking=no ubuntu@${{ secrets.EC2_PUBLIC_IP }} << 'EOF' | |
REPOSITORY_URI=739275468912.dkr.ecr.ap-northeast-2.amazonaws.com/memo-with-tags | |
TAG=$(echo $GITHUB_SHA | cut -c1-7) | |
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin $REPOSITORY_URI | |
docker stop memo-with-tags-backend || true | |
docker rm memo-with-tags-backend || true | |
docker pull $REPOSITORY_URI:$TAG | |
docker run -d --name memo-with-tags-backend -p 80:80 $REPOSITORY_URI:$TAG | |
EOF |