git actions test #1
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: CI/CD with Git Actions & Docker Hub | |
# 워크플로우 트리거: 브랜치에 대한 push 및 pull request 이벤트 발생 시 실행 | |
on: | |
# pull_request: | |
# branches: | |
# - main | |
push: | |
branches: | |
- GitActionsTest | |
jobs: | |
build: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout-source code | |
uses: actions/checkout@v3 | |
- name: Set application.yml | |
run: | | |
mkdir -p ./src/main/resources | |
touch ./src/main/resources/application.yml | |
echo ${{ secrets.APPLICATION_YML }} | base64 --decode >> ./src/main/resources/application.yml | |
- name: Set up JDK 17 | |
uses: actions/setup-java@v3 | |
with: | |
java-version: '17' | |
distribution: 'temurin' | |
- name: Grant execute permission to gradlew | |
run: chmod +x ./gradlew | |
- name: Build with Gradle | |
run: ./gradlew clean build -x test | |
- name: Login docker hub | |
uses: docker/login-action@v2 | |
with: | |
username: ${{ secrets.DOCKERHUB_USERNAME }} | |
password: ${{ secrets.DOCKERHUB_TOKEN }} | |
- 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 | |
- 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 Hub 로그인 | |
docker login -u ${{ secrets.DOCKERHUB_USERNAME }} -p ${{ secrets.DOCKERHUB_TOKEN }} | |
# 기존 컨테이너 중단 및 제거 | |
CONTAINER_NAME="backend" # 컨테이너 이름 (필요시 변경) | |
if [ "$(sudo docker ps -q -f name=$CONTAINER_NAME)" ]; then | |
sudo docker stop $CONTAINER_NAME | |
sudo docker rm $CONTAINER_NAME | |
fi | |
# 최신 이미지를 Pull | |
sudo docker pull ${{ secrets.DOCKERHUB_REPOSITORY }}:backend | |
# 사용하지 않는 Docker 이미지 삭제 | |
sudo docker image prune -f | |
# 새로운 컨테이너 실행 (포트 매핑: 80 -> 8080) | |
sudo docker run -d \ | |
--name $CONTAINER_NAME \ | |
-p 80:8080 \ | |
--log-opt awslogs-stream=backend \ | |
--log-opt awslogs-region=ap-northeast-2 \ | |
${{ secrets.DOCKERHUB_REPOSITORY }}:backend |