본문 바로가기
DevOps/AWS

[DevOps] CICD 구축 전과정 3. 코드 작성, PR, Merge + 도메인 설정

by persi0815 2024. 7. 9.

1. .ebextensions_dev

00-makeFiles.config

files:
    "/sbin/appstart":
        mode: "000755"
        owner: webapp
        group: webapp
        content: |
            #!/usr/bin/env bash
            JAR_PATH=/var/app/current/application.jar

            # run app
            killalljava
            java -Dfile.encoding=UTF-8 -Dspring.profiles.active=develop -jar $JAR_PATH

01-set-timezone.config

commands:
    set_time_zone:
        command: ln -f -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime

시간대 맞추기

2. .github

issue_timeplate는 무시하고 진행하자. 

dev_deploy.yml

: GitHub Actions workflows 설정

*아래의 environment 이름 꼭 ELB 구축할 때 설정한 이름으로 작성해주자!

name: Travel Compass Dev CI/CD

on:
  pull_request:
    types:
      - closed
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'develop'
	# develop branch로 pr 요청되고 merge가 되면 작동
    
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4.0.0
        with:
          java-version: '17'
          distribution: 'adopt'

      - name: Grant execute permission for gradlew
        run: chmod +x gradlew
        shell: bash

      - name: Build with Gradle
        run: ./gradlew clean build -x test
        shell: bash

      - name: Get current time
        uses: josStorer/get-current-time@v2
        id: current-time
        with:
          format: 'YYYY-MM-DDTHH:mm:ss'
          utcOffset: '+09:00'

      - name: Show current time
        run: echo "${{ steps.current-time.outputs.formattedTime }}"
        shell: bash

      - name: Generate deployment package
        run: |
          mkdir -p deploy
          cp build/libs/*.jar deploy/application.jar
          cp Procfile deploy/Procfile
          cp -r .ebextensions_dev deploy/.ebextensions
          cp -r .platform deploy/.platform
          cd deploy && zip -r deploy.zip .

      - name: Deploy to Elastic Beanstalk
        uses: einaregilsson/beanstalk-deploy@v20
        with:
          aws_access_key: ${{ secrets.AWS_ACTION_ACCESS_KEY_ID }}
          aws_secret_key: ${{ secrets.AWS_ACTION_SECRET_ACCESS_KEY }}
          application_name: 'UMC-dev' # 나의 이름으로 조정
          environment_name: 'UMC-dev-env' # 나의 이름으로 조정
          version_label: github-action-${{ steps.current-time.outputs.formattedTime }}
          region: 'ap-northeast-2'
          deployment_package: 'deploy/deploy.zip'
          wait_for_deployment: false

 

3. .platform

client_max_body_size.conf

client_max_body_size 200M;

용량 늘리기

nginx.conf

: 리버스 프록시 설정

user                    nginx;
error_log               /var/log/nginx/error.log warn;
pid                     /var/run/nginx.pid;
worker_processes        auto;
worker_rlimit_nofile    33282;

events {
    use epoll;
    worker_connections  1024;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;


    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    include       conf.d/*.conf;

    map $http_upgrade $connection_upgrade {
        default     "upgrade";
    }

    upstream springboot {
        server 127.0.0.1:8080;
        keepalive 1024;
    }

    server {
        listen        80 default_server;
        listen        [::]:80 default_server;

        location / {
            proxy_pass          http://springboot;
            # CORS 관련 헤더 추가
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
            proxy_http_version  1.1;
            proxy_set_header    Connection          $connection_upgrade;
            proxy_set_header    Upgrade             $http_upgrade;

            proxy_set_header    Host                $host;
            proxy_set_header    X-Real-IP           $remote_addr;
            proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        }

        access_log    /var/log/nginx/access.log main;

        client_header_timeout 60;
        client_body_timeout   60;
        keepalive_timeout     60;
        gzip                  off;
        gzip_comp_level       4;

        # Include the Elastic Beanstalk generated locations
        include conf.d/elasticbeanstalk/healthd.conf;
    }
}

 

4. Procfile

web: appstart

 

5. build.gradle의 jar 비활성화

jar {
    enabled = false
}

 

6. rootController 작성

: health check 위해

@Controller
public class RootController {

    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }

}

 

 

7. yml에서 develop부분 추가

# local profile
spring:
  config:
    activate:
      on-profile: local
  datasource:
    url: ${local.db.url}
    username: ${local.db.username}
    password: ${local.db.password}
    driver-class-name: com.mysql.cj.jdbc.Driver
  sql:
    init:
      mode: never
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect
        #        format_sql: true
        #        show_sql: true
        use_sql_comments: true
        hbm2ddl:
          auto: create
        default_batch_fetch_size: 1000

---

# develop profile
spring:
  config:
    activate:
      on-profile: develop
  datasource:
    url: ${aws.db.url}
    username: ${aws.db.username}
    password: ${aws.db.password}
    driver-class-name: com.mysql.cj.jdbc.Driver
  sql:
    init:
      mode: never
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect
        #        format_sql: true
        #        show_sql: true
        use_sql_comments: true
        hbm2ddl:
          auto: update
        default_batch_fetch_size: 1000

 

8. PR, Merge

기존에 설정해놨던 걸 수정을 안해줘서 문제가 좀.. 생겼었지만 그래도 성공!!

 

이렇게 degraded되었다가 시간이 지나면, ok로 바뀌니까 너무 걱정하지 말고 기다리면..!

이렇게 영롱한 초록빛깔의 OK가 뜬다!!

 

9. 리스너에 8080 포트 추가

이래야 8080포트를 사용할 수 있게 된다. 

 

10. 서브 도메인 만들기

나는 미리 가비아에서 사놓은 persi0815라는 도메인이 있다. 

해당 도메인을 이용해 서브 도메인을 만들어 볼 예정이다. 

Route 53에서 추가해놓은 도메인에 들어가서 record를 다음과 같이 해주면 된다. 

 

 

11. 신나는 결과물 확인

시간 갖고 좀만 기다리면 도메인에서 이렇게 health check를 눈으로 확인할 수 있다. 

 

swagger도 잘 된다!!

 

 

이어서 HTTPS 설정도 하고 싶다면..!

https://persi0815.tistory.com/38