Git Action

준비 환경

  • Amazon RDS (mysql , postgresql 중 택1, 포트 설정)
  • AWS EC2 (node.js, jdk17, Docker 등 필요한 기능 설치되어있어야함, 22, 8080, 80 포트 설정)
  • Elastic IP 설정 (고정 IP 필수)

deploy.yml 파일 생성

  1. 깃 최상위 경로에 /.github/workflows/deploy.yml 폴더와 파일을 생성한다. (경로와 파일명이 동일해야 git에 인식됨)
  2. deploy.yml 에 자신의 프로젝트 환경에 맞는 빌드 스크립트를 작성한다.

ex. Demo project 의 경우 Frontend (React+Vite) 와 Backend (SpringBoot) 이고, 프론트 dist 파일을 Backend static 에 올려서 함께 배포한다.

name: Deploy to EC2

on:
  push:
    branches: [ feature/awscicd ]  # 배포 원하는 브렌치 설정

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    env:
      GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
      GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
      # ... 환경변수들 git 에서 설정

    steps:
      - name: Checkout 코드
        uses: actions/checkout@v3

      - name: Node.js 설치
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Frontend Build
        run: |
          cd frontend
          npm ci
          npm run build
          cp -r dist/* ../backend/src/main/resources/static/  # Front 경로 맞추기

      - name: EC2에 .env 파일 생성
        uses: appleboy/ssh-action@v0.1.10
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_SSH_KEY }}
          script: |
            mkdir -p /home/ec2-user/app/backend/build/libs  # Backend 경로 맞추기
            cd /home/ec2-user/app/backend/build/libs

            echo "GOOGLE_CLIENT_ID=${{ secrets.GOOGLE_CLIENT_ID }}" > .env
            echo "GOOGLE_CLIENT_SECRET=${{ secrets.GOOGLE_CLIENT_SECRET }}" >> .env
            # ...
            
            echo "======= .env 파일 생성 완료 ==========="

            echo "======== .env 내용 확인 ========="
            cat .env

            echo "======== 환경변수 적용 ========"
            # 환경변수 적용
            if [ -f .env ]; then
              echo ".env 파일이 존재합니다. 환경변수를 적용합니다."
              set -a
              source .env
              set +a
            else
              echo ".env 파일이 존재하지 않습니다. 배포를 중단합니다."
              exit 1
            fi

      - name: Backend Build
        run: |
          cd backend
          chmod +x ./gradlew
          ./gradlew build --no-daemon -x test  # 테스트 설정

      - name: EC2에 JAR 파일 복사
        uses: appleboy/scp-action@v0.1.4
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_SSH_KEY }}
          source: "backend/build/libs/*.jar"   # 경로 맞추기
          target: "/home/ec2-user/app/"

      - name: EC2에서 JAR 실행
        uses: appleboy/ssh-action@v0.1.10
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USERNAME }}
          key: ${{ secrets.EC2_SSH_KEY }}
          script: |
            cd /home/ec2-user/app/backend/build/libs

            echo "======== JAR 파일 확인 ========"  # 파일명 확인
            ls -al backend-0.0.1-SNAPSHOT.jar || echo "=== JAR 파일이 존재하지 않습니다"

            echo "======== 자바 실행 ========="
            nohup java -jar backend-0.0.1-SNAPSHOT.jar > app.log 2>&1 & disown
            sleep 5

            echo "======== 실행된 자바 프로세스 확인 ========"
            pgrep -af java || echo "실행 중인 자바 없음"

            echo "========= 자바 로그 출력 ========"
            tail -n 50 app.log

참고

  • pkill -f 'java' || true 이걸 넣으면 Git Action 프로세스까지 다 정지되어서 다른 방법 찾아야함. → pm2로 jar 관리가능
  • disown 제거해도됨.
  • profiles 설정 (--spring.profiles.active=dev 추가)
nohup java -jar backend-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev > app.log 2>&1 & disown

해당 최상단 위치에서 deploy.yml 커밋 후 실행하고 싶지만 GitHub은 2021년부터 패스워드 방식 인증을 막았기 때문에GitHub 비밀번호로는 더 이상 PUSH 안됨. → ssh key 생성 필요

 


 

Git 용 SSH Key 생성

1. git commit HTTPS → SSH 인증 방식으로 바꾸기

  1. git 폴더 경로 터미널에서 ssh 키 만들기 (이미 있으면 생략):
ssh-keygen -t rsa -b 4096 -C "hellou@example.com"

Enter passphrase for "cat ~/.ssh/id_rsa.pub" (empty for no passphrase): 다 엔터로 그냥 넘어가기

    2. 공개키 확인하기

cat ~/.ssh/id_rsa.pub
ssh-rsa A~~~~~~~~

2. git settings 에 등록

  1. GitHub → Settings > SSH and GPG keys → New SSH Key → 붙여넣기
  • 아까 ssh-rsa 로 시작했던 값 입력하기 

   2. GitHub remote 주소 변경:

git remote set-url origin git@github.com:{자신의 git 리포지토리 주소}

 


 

deploy.yml 실행

git add .
git commit -m "ci: github actions 배포 추가"
git push origin develop
  • 배포 원하는 브랜치인지 확인할것

 

GitHub 에서 Action 워크플로우 확인

  1. GitHub 레포 열기
  2. 상단 탭 중에서 Actions 클릭
  3. Deploy to EC2 워크플로우가 실행되고 있는지 확인
  4. 각 step(log)을 클릭해서 npm, gradle, ssh, scp 성공 여부 확인

 


 

EC2 서버에서 배포확인

  1. .env 파일이 잘 생성되었는지 확인
  2. jar 파일이 경로에 생성되었는지 확인
  3. app.log 로 app 실행 로그 확인
  4. 디비 연결 잘 되는지 확인
  • EC2에서 AWS RDS 연결 테스트 (생성한 DB 환경에 맞춰 수정하여 테스트)
psql -h database 엔드포인트 \\
     -p 5432 \\
     -U name_a \\
     -d demodb

# jdbc:postgresql://{database앤드포인트}:5432/{dbname}
  • 연결 성공 시:
psql (16.1, server 13.4)
Type "help" for help.

demodb=>
  • 전체 테이블 보기 (현재 스키마 기준)
\\dt

 

  5. EC2 서버와 연결된 Elastic IP 로 접속하면 된다.

 


 

Git secrets text 환경변수 설정

  1. Repository 에 필요한 환경변수들을 적용한다.

https://www.bbc.com/news/articles/c629q4v05pwo

 

Paris Baguette: The Korean bakery that wants to make croissants less French

Asian bakeries are seeing success at home and abroad by bringing global flavours to traditional French pastries.

www.bbc.com

The Korean bakery chain that says croissants don't have to be French

 

Head into the basement of any bustling mall in Singapore and the chances are you will smell the sweetness of fresh, buttery baked goods.

...

He credits his company's system of delivering frozen dough to franchises around the world for improving efficiency and extending shelf life.

...

 

1. 단어

  • swarm               1. 명사 (한 방향으로 이동하는 곤충의) 떼[무리], 벌 떼 2. 명사 (특히 같은 방향으로 급히 이동 중인) 군중[대중] (=horde) 3. 동사 흔히 못마땅함 떼[무리]를 지어 다니다
  • ambience         분위기
  • knead dough   반죽을 치대다, 주무르다
  • shelf life            (식품) 유통기한
  • urbanization     도시화
  • artisanal bakery    형용사 공예가의, 장인(匠人)의.
  • elasticity                 명사 탄성, 탄력성

 

2.요약

Paris Baguette is expanding internationally, aiming to capture the global market. They've developed a frozen-dough system delivered to franchisees to optimize cost and efficiency, and they hope to share Korean baking culture through their bread.

 

 

https://www.bbc.com/news/articles/c87jq0djw00o

 

Trump-Musk row fuels 'biggest crisis ever' at Nasa

The space agency has published its budget request to Congress which would see funding for science projects cut by nearly a half.

www.bbc.com

 

Trump-Musk row heightens fears over Nasa budget cuts

...

But, Mr Dreier worries that there is a strong possibility that political gridlock might mean that no budget is agreed.

It is likely that the reduced White House budget would be put in place as an interim measure, which then could not easily be reversed, because once space missions are turned off it is hard, if not impossible, to start them up again.

...

 

 

1. 단어

  • jeopardize                     동사 격식 위태롭게 하다 (=endanger)
  • feud                              1. 명사 (오랜 동안의) 불화[반목] 2. 동사 불화를 빚다, 반목 속에 지내다
  • earmark                       1. 동사 (특정 목적용으로) 배정[결정/예정]하다 2. 명사 美 (전형적인) 특징[특질]
  • bloated                           비대해진, 불필요하게 커진 (↔ lean)
  • unfocussed                   초점이 없는, 방향이 분산된 
  • bureaucracy                 관료조직
  • egregious                       형용사 격식 지독한
  • bankroll                          1. 동사 비격식 재정을 지원하다, 돈을 대다 (=finance) 2. 명사 재정 지원
  • political gridlock           정치적 교착 상태
  • put in place                    시행하다
  • interim measure            임시 조치
  • it is hard, if not impossible, to      불가능하지는 않더라도 거의 어렵다

 

2. 요약

The feud between Trump and Musk might lead to cuts in NASA’s science budget, delaying both space and climate research - and once halted, space missions may be difficult to restart.

 

https://www.npr.org/transcripts/1253689645

 

'Bring Her Back' makes us squirm in ways we couldn't have imagined : Pop Culture Happy Hour

The hit Australian horror movie Talk To Me was both very good and deeply unsettling. Now its directors (Danny and Michael Philippou) have returned with Bring Her Back, which ups the ante when it comes to disturbing, nightmarish storytelling. The film stars

www.npr.org

 

'Bring Her Back' makes us squirm in ways we couldn't have imagined

 

The hit Australian horror movie Talk to Me was both very good and deeply unsettling. Now its directors have returned with Bring Her Back, and they've upped the ante when it comes to disturbing, nightmarish storytelling. It stars Sally Hawkins as a woman whose grief manifests in terrifying and ugly ways. 

 

...

 

 

 

1. 단어

upped the ante             (특히 돈의 액수나 요구 등의) 정도를 높이다, 수위(강도)를 높이다

manifests                         나타내다, 드러내다 

recoil                                 1. 동사 (무섭거나 불쾌한 것을 보고) 움찔하다[흠칫 놀라다] (=flinch) 

                                        2. 동사 (어떤 생각·상황에 대해 혐오감·공포심으로) 움츠러들다 (=shrink)

on the vanguard            최전선에 있다, 선두에 있다

devastating                   엄청나게 충격적인

seldom                            = rarely

atavistic                          원시적인, 원초적인, 조상으로부터 유전된

it didn't jibe for me.      공감되지 않았다, 나에겐 맞지 않았다

embattled                        (비유적) 어려움에 처한, 갈등이 있었던

it feels so earned          (감정이나 결말 등이) 정당하게 얻어진, 진정성이 있는 

 

 

2. 요약

The reactions to the movie are highly polarized.

 

 

 

https://www.theguardian.com/world/2025/jun/06/measles-outbreak-ontario-canada

 

A massive outbreak has made Ontario the measles epicentre of the western hemisphere

Three-quarters of cases are in unvaccinated children, and this week saw the first fatality: a premature baby

www.theguardian.com

 

 

A massive outbreak has made Ontario the measles epicentre of the western hemisphere

Three-quarters of cases are in unvaccinated children, and this week saw the first fatality: a premature baby

 

...

 

To see such an imperative in the 21st century might have been previously unimaginable for Canada, which in 1998 achieved “elimination status” for measles, meaning the virus is no longer circulating regularly.

 

Now, however, Canada is at risk of losing that status – mainly because of an explosive outbreak of the highly infectious and sometimes deadly disease in south-western Ontario, where the St Thomas hospital is located.

 

...

 

A confluence of antiquated local public health vaccination strategies, sparse access to family doctors, delays in routine immunization due to Covid-19 and a surge in vaccine hesitancy propelled by online misinformation since the pandemic all have contributed to the crisis.

 

...

 

 

1. 단어

measles                                 홍역

epicentre                            중심지, 진원지

fatality                                   1. 명사 (재난·질병 등으로 인한) 사망자 2. 명사 치사율 3. 명사 운명을 피할 수 없다는 생각, 숙명론

a premature baby              미숙아

imperative                            1. 형용사 격식 반드시 해야 하는, 긴급한 (=vital)     2. 명사 긴급한 사태

elimination                           퇴치, 근절, 제거

explosive outbreak           폭발적 발생

infectious                            1. 형용사 전염되는[전염성의] 2. 형용사 병을 옮길 수 있는 (→contagious)

staggering                            형용사 (너무 엄청나서) 충격적인, 믿기 어려운 (=astounding)

medical complications    합병증

paediatrics                           소아과

A confluence of                 여러 요소들의 결합 (합류점, 융합)

antiquated                           형용사 보통 못마땅함 구식인 (=outdated)

sparse                                 희박한

routine immunization       정기예방접종

 

 

2. 요약

A significant measles outbreak is unfolding in Ontario due to a confluence of outdated policies and widespread misinformation. The government should urgently implement effective strategies to rebuild public trust in routine immunizations and prevent future outbreaks.

 

 

 

 

+ Recent posts