ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • EC2 서버에 프로젝트 배포하기 (EC2 ./gradlew test 무한 로딩, nohub java ~ application-real-db.properties 오류)
    AWS 2023. 11. 9. 13:50

    참고 : 스프링 부트와 AWS로 혼자 구현하는 웹 서비스

     

    1. EC2에 프로젝트 Clone 받기

    # EC2에 깃 설치
    sudo yum install git
    
    # 설치 상태 확인
    git --version
    
    # git clone으로 프로젝트를 저장할 디렉토리 생성
    mkdir ~/app && mkdir ~/app/step1
    
    # 생성된 디렉토리로 이동
    cd ~/app/step1
    
    # git clone 진행
    git clone 복사한 주소

     

     

    git clone 정상 실행 확인

     

    # 코드 정상 수행 확인
    ./gradlew test
    
    # -bash: ./gradlew: Permission denied
    # 하기 명령어로 권한 부여 후 ./gradlew test
    chmod +x ./graldew

     

    ※ ./gradlew test  EC2 중단 현상

    해당 명령어 실행 시 EC2 서버가 먹통이 되는 현상이 발생했다.

    30분 넘게 멈춘 상태로 종료도 되지 않고 아무것도 할 수 없는 상태 ..

    인스턴스 중단 후 재실행하면 서버 접속은 잘 되었다.

      

    인스턴스 모니터링을 확인해보니 CPU 사용률이 99%였고 상태검사 중 하나가 실패로 되어있었다.

    ./gradlew test 만 입력하면 서버가 중단되었다.

    (./gradlew clean build -x test 으로 테스트 코드 제외 후 빌드 시에는 잘 동작 됨)

     

    하기 블로그 참고하여 메모리 스왑 적용하니 해결되었다.

     

    https://sundries-in-myidea.tistory.com/102

     

    AWS EC2 프리티어에서 메모리 부족현상 해결방법

    AWS free tier를 사용하다보면 2%가 부족할 때가 있다. AWS 프리티어는 가난한 대학생에게는 한줄기 빛과 같은 존재인데, AWS의 프리티어라서 적게 돈이 나가는 것도 좋고, 실제로 이것저것 해볼 수 있

    sundries-in-myidea.tistory.com

     

     

    2. 배포 스크립트 만들기

    # 배포 스크립트 파일 생성
    vim ~/app/step1/deploy.sh

     

    deploy.sh

    application-oauth.properties는 3. 외부 Security 파일 등록하기

    application-real-db.properties, application-real.properties는 4. 스프링 부트 프로젝트로 RDS 접근하기에서 생성

    #!/bin/bash
    
    REPOSITORY=/home/ec2-user/app/step1
    PROJECT_NAME=freelec-springboot2-webservice
    
    cd $REPOSITORY/$PROJECT_NAME/
    
    echo "> Git Pull"
    
    git pull
    
    echo "> 프로젝트 Build 시작"
    
    ./gradlew build
    
    echo "> step1 디렉토리로 이동"
    
    cd $REPOSITORY
    
    echo "> Build 파일 복사"
    
    cp $REPOSITORY/$PROJECT_NAME/build/libs/*.jar $REPOSITORY/
    
    echo "> 현재 구독 중인 애플리케이션pid 확인"
    
    CURRENT_PID=$(pgrep -f ${PROJECT_NAME}.*.jar)
    
    echo "현재 구동 중인 애플리케이션 pid: $CURRENT_PID"
    
    if [ -z "$CURRENT_PID" ]; then
            echo "> 현재 구동 중인 애플리케이션이 없으므로 종료하지 않습니다."
    else
            echo "> kill -15 $CURRENT_PID"
            kill -15 $CURRENT_PID
            sleep 5
    fi
    
    echo "> 새 애플리케이션 배포"
    
    JAR_NAME=$(ls -tr $REPOSITORY/ | grep jar | tail -n 1)
    
    echo "> JAR Name: $JAR_NAME"
    
    nohup java -jar \
    	-Dspring.config.location=classpath:/application.properties,/home/ec2-user/app/application-oauth.properties,/home/ec2-user/app/application-real-db.properties,classpath:/application-real.properties 
    	-Dspring.profiles.active=real \
    	$REPOSITORY/$JAR_NAME 2>&1 &

     

    ※ nohub java ~ application-real-db.properties 설정 추가 후 배포 실패 오류

    application-real-db.properties 관련 추가 설정 후 application-oauth.properties가 없을 때 발생하는 오류가 나타났다.

    Bean method 'clientRegistrationRepository' in 'OAuth2ClientRegistrationRepositoryConfiguration' not loaded
    because Outh2 Clients Configured Condition registered clients is not available
    
    Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client. registration.ClientRegistrationRepository' in your
    configuration.

     

    해당 파일을 제대로 읽어오지 못 하는 문제로 해당 부분 \ 삭제, 줄바꿈 없게 변경하였더니 정상 실행되었다.

    nohub java -jar ~ 수정

     

     

    3. 외부 Security 파일 등록하기

    application-oauth.properties 파일이 .gitignore에 등록되어 있어 로컬 PC에서는 정상 실행되나 EC2 서버에서 빌드 실패

     서버에서 직접 이 설정들을 가지고 있게 적용

    # app 디렉토리에 properties 파일 생성
    vim /home/ec2-user/app/application-oauth.properties

     

    application-oatuh.properties

    local의 application-oauth.properties 내용 copy하여 동일하게 생성

    spring.security.oauth2.client.registration.google.client-id=xxxxxxxxxx
    spring.security.oauth2.client.registration.google.client-secret=xxxxxxxxxx
    spring.security.oauth2.client.registration.google.scope=profile,email
    
    # registration
    spring.security.oauth2.client.registration.naver.client-id=xxxxxxxxxx
    spring.security.oauth2.client.registration.naver.client-secret=xxxxxxxxxx
    spring.security.oauth2.client.registration.naver.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
    spring.security.oauth2.client.registration.naver.authorization_grant_type=authorization_code
    spring.security.oauth2.client.registration.naver.scope=name,email,profile_image
    spring.security.oauth2.client.registration.naver.client-name=Naver
    
    # provider
    spring.security.oauth2.client.provider.naver.authorization_uri=https://nid.naver.com/oauth2.0/authorize
    spring.security.oauth2.client.provider.naver.token_uri=https://nid.naver.com/oauth2.0/token
    spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me
    spring.security.oauth2.client.provider.naver.user_name_attribute=response

     

     

     

    4. 스프링 부트 프로젝트로 RDS 접근하기

    (1) build.gradle에 MariaDB 드라이버 등록

    compile("org.mariadb.jdbc:mariadb-java-client")

     

    (2) 서버에서 구동될 환경 구성

    * 프로젝트 설정

    src/main/resouces/application-real.properties 파일 추가

    • profile=real인 환경이 구성됨
    • 실제 운영될 환경이기 때문에 보안/로그상 이슈가 될 만한 설정들을 모두 제거하여 RDS 환경 profile 설정 추가
    spring.profiles.include=oauth,real-db
    
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
    spring.jpa.properties.hibernate.dialect.storage_engine=innodb
    
    spring.session.store-type=jdbc
    spring.session.jdbc.initialize-schema=always
    
    server.servlet.encoding.charset=UTF-8
    server.servlet.encoding.force=true

     

     

    * EC2 설정

    OAuth와 마찬가지로 RDS 접속 정보도 보호해야 할 정보이므로 EC2 서버에 직접 설정 파일 추가

    # app 디렉토리에 application-db.properties 파일을 생성
    vim ~/app/application-real-db.properties

     

    application-real-db.properties

    spring.jpa.properties.hibernate.format_sql=true
    logging.level.org.hibernate.SQL=debug
    logging.level.org.hibernate.type=trace
    
    spring.datasource.hikari.jdbc-url=jdbc:mariadb://rdsa주소:포트명(기본은 3306)/database이름
    spring.datasource.hikari.username=db계정
    spring.datasource.hikari.password=db계정 비밀번호
    spring.datasource.hikari.driver-class-name=org.mariadb.jdbc.Driver
    
    spring.jpa.hibernate.ddl-auto=none

     

     

    'AWS' 카테고리의 다른 글

    Nginx 무중단 배포  (0) 2023.11.10
    Travis CI 배포 자동화 (Travis CI repository 연동 오류)  (0) 2023.11.09
    Mac/Linux EC2 서버 접속하기  (0) 2023.11.08

    댓글

Designed by Tistory.