AWS

AWS Elastic Beanstalk + Java or Kotlin 배포 방법

Dexlee 2022. 7. 3. 22:00

1. EB 배포 시 필요한 파일

1) application.jar

  • 배포 시 필요한 코드, 라이브러리, 설정이 포함되어 있다.
  • jar 파일은 zip 파일이다.

[1] jar 파일 실행 방법

java -Dfile.encoding=UTF-8 -jar application.jar

[2] 내부 파일 목록을 보고 싶을 때 사용하는 명령어.(배포와는 관련 없다.)

(1) jar 파일 추출 방법 

jar -xvf application.jar

(2) jar 파일 목차 보는 방법

jar -tvf application.jar

 

2) .ebextensions

  • eb 커스터마이징 설정

3) .platform

  • nginx 등 eb 설정이 아닌 설정 파일을 보관하는 디렉토리

4) Procfile

  • 설정 파일을 실행시키기 위한 파일
  • 만약에 jar 파일만 넘긴다면 Procfile이 필요없다.

2. Jar 파일 생성 방법

./gradlew clean bootjar

 

3. .ebextensions 생성 방법

1) 애플리케이션 최상단에 파일을 생성한다.

/.ebextensions

2) 설정 파일 생성 방법

.ebextensions/00-name.config

  • 이러한 방식으로 처음에 순서를 준다. 00, 01 등
  • 그 후 '-', 해당 config 파일 이름을 적어준다. 
    • ex) 00-makefile.config
  • 만약 순서가 중요하지 않다면 그냥 name.config로 파일명을 생성하면 된다.

3) .ebextensions/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
            killall java
            java -Dfile.encoding=UTF-8 -jar $JAR_PATH
  • /sbin 아래에 스크립트 파일을 두면 전역에서 실행 가능
  • mode 권한을 의미
  • owner는 사용자로 webapp 으로 설정
  • content 내용을 가진 스크립트 파일 실행

 

4. .platform 생성 방법

1) 애플리케이션 최상단에 파일을 생성한다.

/.platform

2) nginx 설정 파일 생성 방법

.platform/nginx/nginx.conf 파일을 만든다.

3) nginx.conf

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

events {
    worker_connections  1024;
}

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";
    }

    server {
        listen        80 default_server;
        access_log    /var/log/nginx/access.log main;

        client_header_timeout 600;
        client_body_timeout   600;
        keepalive_timeout     600;
        proxy_connect_timeout 600;
        proxy_send_timeout 600;
        proxy_read_timeout 600;
        send_timeout 600;
        gzip                  off;
        gzip_comp_level       4;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        include conf.d/elasticbeanstalk/*.conf;
    }

    client_max_body_size 1024M;
}
  • 이 파일을 만들 때 중요한 점은 주석이 없는 것이 오류가 발생할 확률을 줄일 수 있다.

5. Procfile 생성방법

1) 애플리케이션 최상단에 파일을 생성한다.

/Procfile

2) Procfile

web: appstart
  • 00-makefiles.config 에서 설정한 appstart를 실행시킨다.

 

6. AWS EB 배포 zip 파일 생성

$ mkdir -p deploy
$ cp -r .ebextensions deploy/.ebextensions
$ cp -r .platform deploy/.platform
$ cp build/libs/*.jar deploy/application.jar
$ cp Procfile deploy/Procfile
$ cd deploy && zip -r deploy.zip .
  • deploy 디렉터리를 만든다.
  • .ebextensions, .platform, *.jar, Procfile 을 deploy 디렉터리에 넣는다.
  • deploy.zip 파일을 만든다.

ps. zip -r name.zip .

여기서 -r 옵션은 하위 디렉터리까지 압축하라는 의미이다

 

7. AWS EB 특징

  • 애플리케이션 하위에 환경이 존재한다.
  • , 애플리케이션이 상위이고, 애플리케이션 아래에 여러 환경이 만들어지는 구조가 EB 특징이다.

 

8. AWS EB에 업로드

새 환경 만들기

 

 

여기에서 deploy.zip을 업로드 하면 된다.

추가 옵션 구성 버튼을 클릭한다.

 

사용자 지정 구성 클릭

 

편집 클릭

  • 환경 속성에서 SERVER_PORT 를 지정해준다.
  • 만약에 DB 설정을 application.yml 에 지정하지 않았다면, 여기에서 환경변수 설정을 해준다.

 

EC2 카테고리에 있는 보안 그룹 카테고리에서 EB 보안 그룹 만들고 적용할 것

  • 인스턴스 성능 지정
  • 로드 밸런싱을 사용한다면 인스턴스를 몇 개까지 사용할지 지정

 

로블 밸런서 유형은 application 기본값 사용
배포 방식을 추가 배치를 사용한 롤링으로 변경

 

  • 이렇게 설정 후 EB 실행하면 정상적으로 작동 될 것이다.
  • 또한, CI/CD 자동 배포를 하기 위해 actionhub action 을 같이 사용해주면 push 명령어 하나로 자동 배포를 구축할 수 있다.

ps. 이렇게 설정하고 끝내면 정상 작동이 될까?

 

9. errors

1) health 체크 에러

  • EB는 health 체크를 자동적으로 하는데, 이 때 해당 request를 받지 못 하면 EB가 정상적으로 작동하지 않는다.
  • 그래서 health 체크 request를 받아주는 api를 만들어줘야 EB가 정상 작동한다.

[1] 해결책

  • EB는 health를 /health, / url로 request를 보낸다.
  • 그러므로 해당 response를 만들어주면 된다.

CheckController.kt

import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class CheckController {
    @Value("\${spring.profiles.active}")
    private val profile: String? = null

    @RequestMapping(value = ["/health", "/"])
    fun healthCheck(): ResponseEntity<String> {
        return ResponseEntity("Spring Boot server-name application($profile) !!!", HttpStatus.OK)
    }
}

 

 

 

references

1) .ebextensions 

https://techblog.woowahan.com/2539/

 

2) eb 설정

https://docs.aws.amazon.com/ko_kr/elasticbeanstalk/latest/dg/using-features.rolling-version-deploy.html

 

3) spring boot - deploy - aws EB : port settings

https://www.typeerror.org/docs/spring_boot/deployment#aws-elastic-beanstalk

 

4) eb error - health 체크

https://docs.aws.amazon.com/ko_kr/elasticbeanstalk/latest/dg/using-features.healthstatus.html

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-clb.html#using-features.managing.elb.healthchecks

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#command-options-general-elasticbeanstalkapplication

 

https://discourse.metabase.com/t/aws-eb-setup-failing-due-to-health-check/55

: 아래 답변에서 ec2 instance health check 이미지 확인

 

5) zip 명령어

https://coding-factory.tistory.com/805