Skip to content

Workflow file for this run

name: CI/CD with Git Actions & Docker Hub
# 워크플로우 트리거: 브랜치에 대한 push 이벤트 발생 시 실행..
on:
push:
branches:
- main
# pull_request:
# branches:
# - main
jobs:
build:
runs-on: ubuntu-latest
steps:
# 소스 코드를 체크아웃
- name: Checkout source code
uses: actions/checkout@v3
# application.yml 파일 생성
- name: Set application.yml
run: |
mkdir -p ./src/main/resources
echo "${{ secrets.APPLICATION_YML }}" > ./src/main/resources/application.yml
# Open JDK 17 설정
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
# Gradle 실행 권한 부여
- name: Grant execute permission to gradlew
run: chmod +x ./gradlew
# Spring Boot 애플리케이션을 Gradle로 빌드 (테스트 제외)
- name: Build with Gradle
run: ./gradlew clean build -x test
# Docker Hub에 로그인
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# Spring Boot 애플리케이션의 Docker 이미지를 빌드하고 Docker Hub에 푸시
- name: Build and push Spring Boot app Docker image
run: |
docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_REPOSITORY }}:backend --platform linux/amd64 .
docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_REPOSITORY }}:backend
# EC2 인스턴스에서 Docker 이미지를 pull하고 애플리케이션을 배포
- name: Deploy at EC2 instance
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ubuntu
key: ${{ secrets.SSH_KEY }}
port: ${{ secrets.SSH_PORT }}
script: |
docker login -u "${{ secrets.DOCKERHUB_USERNAME }}" -p "${{ secrets.DOCKERHUB_TOKEN }}"
CONTAINER_NAME="backend"
sudo docker stop $(sudo docker ps -q) || true
sudo docker rm $(sudo docker ps -a -q) || true
sudo docker rmi $(sudo docker images -q) || true
sudo docker pull "${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_REPOSITORY }}:backend"
sudo docker run -d \
--name "$CONTAINER_NAME" \
-p 80:8080 \
"${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_REPOSITORY }}:backend"