Infra/AWS

[AWS] EC2 에 Spring boot 올리는 과정 및 삽질 (with java 17 + spring boot3.0)

민돌v 2023. 2. 10. 18:43
728x90

 

간단하게, aws 에 ec2를 생성하여 처음부터, git hub에 올라가있는 spring boot project를 구동시키는 과정을 기록한 글입니다.

 

시나리오

  1. aws ec2 신규 생성
  2. 보안 그룹 out/inbound 오픈
  3. ec2에 java 17, gradle 설치
  4. ec2에 git clone
  5. ec2에 프로젝트 빌드
  6. ec2 spring 백그라운드 실행

 

순서대로 해보겠습니담


1. EC2 생성 및 JAVA 17설치

 EC2 생성및 inbound port 열기는 여기 참고

  • → 그사이에 aws 가 바뀌긴 했지만 얼추비슷하게 ubuntu 에 프리티어로 생성

ec2 생성


2 EC2 터널링 접속

//ssh -i 받은키페어를끌어다놓기 ubuntu@AWS에적힌내아이피(인스턴스 퍼블릭 ipv4 주소)

ex)
ssh -i /path/my-key-pair.pem ubuntu@13.125.250.20

3 EC2 JAVA 설치 

sdkman 을 다운받을 떄 필요한 패키지 없다하면 메세지 그대로 다운받으면 됩니다. 저는 아래 2가지 라이브러리를 추가적으로 다운받아서 사용하였습니다.

sudo apt-get install zip

sudo apt-get install unzip

 


4. git clone 및 build gradle

여기서 문제 발생

 

1) 첫번쨰 에러

📌 먼저 혹시 몰라 gradle 을 sdkman 을 이용하여 7.5.1 버전을 다운받고 빌드를하니 첫번째 에러를 만났습니다.

  • sudo apt-get install gradle
  • ./gradlew build 
FAILURE: Build failed with an exception.

* What went wrong:
Gradle could not start your build.
> Could not create service of type ChecksumService using BuildSessionScopeServices.createChecksumService().
   > java.io.FileNotFoundException: /home/ubuntu/THT-Server/api/.gradle/7.5.1/checksums/checksums.lock (Permission denied)

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s

FAILURE: Build failed with an exception.

* What went wrong:
Could not update /home/ubuntu/THT-Server/api/.gradle/7.5.1/fileChanges/last-build.bin
> /home/ubuntu/THT-Server/api/.gradle/7.5.1/fileChanges/last-build.bin (Permission denied)

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s

 

📌  혹시 gradle 버전이 안맞아서 그런가 싶어 ec2 에 SDKMAN으로 gradle 버전 업데이트 

  • gradle --version

📌  sdkman install gradle 7.5.1 (java랑 똑같이 lsit 확인하고 버전 다운받으면 됩니다.)

그래도 실패


2) 두번째 에러 (spring boot3.0 - java version error)

📌  구글링을 하면 gradle 중복이라고 나오지만, sudo 로 실행 → 두 번째. 에러를 만났습니다.

  • 분명히 java 17을 다운받고 JAVA_HOME 한경설정도 /etc/profile 에 작성해주었지만 gradle 이 11버전을 참조한다고 나옵니다.

오 새로운 에러

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'api'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:3.0.0.
     Required by:
         project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.0.0
      > No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.0.0 was found. The consumer was configured to find a runtime of a library compatible with Java 11, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '7.5.1' but:
          - Variant 'apiElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.0 declares a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component compatible with Java 17 and the consumer needed a runtime of a component compatible with Java 11
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')
          - Variant 'javadocElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.0 declares a runtime of a component, and its dependencies declared externally:
              - Incompatible because this component declares documentation and the consumer needed a library
              - Other compatible attributes:
                  - Doesn't say anything about its target Java version (required compatibility with Java 11)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')
          - Variant 'mavenOptionalApiElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.0.0 declares a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares an API of a component compatible with Java 17 and the consumer needed a runtime of a component compatible with Java 11
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')
          - Variant 'mavenOptionalRuntimeElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.0.0 declares a runtime of a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 11
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')
          - Variant 'runtimeElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.0 declares a runtime of a library, packaged as a jar, and its dependencies declared externally:
              - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 11
              - Other compatible attribute:
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')
          - Variant 'sourcesElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.0.0 declares a runtime of a component, and its dependencies declared externally:
              - Incompatible because this component declares documentation and the consumer needed a library
              - Other compatible attributes:
                  - Doesn't say anything about its target Java version (required compatibility with Java 11)
                  - Doesn't say anything about its elements (required them packaged as a jar)
                  - Doesn't say anything about org.gradle.plugin.api-version (required '7.5.1')

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

 

📌 EC2 에서 jdk 11 을 다운받은적이 없으니 → Linux os 에서 뭐가 있나 하고 탐색 (Linux find 참고

find / -name "*jdk*" | grep 11

 

CentOS 와 Ubuntu 에 OpenJDK 가 기본 탑재되면서 JDK 은 /usr/lib/jvm 아래에 설치된다고 합니다.

따라서 gradle 이 실행될 때 이 /usr/lib/jvm 경로 아래 java 11 버전을 참조해서 계속 오류가 나는게 아닐까.. 추측입니다.

 

2가지 방법을 시도해보았습니다.

⬇️

 

👏🏻 1. JAVA_HOME 환경변수 전역 설정

  • JAVA_Home 을 분명하게 /etc/profile 에 설정해주고 경로도 잘 나오지만, 뭔가 되지않아 찾아보니 
  • /etc/environment 파일안에 전역적으로 환경변수를 설정해 줄 수 있다고 해서 바로 해보았습니다.
 
1) Set environment variable
vim으로 /etc/environment 열기
 
$ sudo vi /etc/environment​
 

2) 환경변수 추가하기

export JAVA_HOME=다운받은 sdkman java 17 경로
  • 필요하다면 Java Path 도 설정을 해주어야 Java --version 시 버전 적용이 잘되었음을 확인할 수 있습니다.

   vi /etc/profile 에 들어가서 맨밑에 추가

$ export PATH=$PATH:$JAVA_HOME/bin
$ export CLASSPATH=.:$JAVA_HOME/lib/tools.jar

 

3) 수정된 값 적용
source 명령어로 수정된 값 바로 적용하기
$ source /etc/environment

/etc/environment 작성


👏🏻 2. gradle.properties

  • 이건 사실 제가 해본것은 아니고, 팀자님에게 여쭤봐서 알게된건데, 어짜피 gradle 이 실행될 떄 JAVA 경로를 잘 못찾는 거 같으니
  • gradle.properties 파일을 생성하여 해당 폴덜에서 gradle 실행 환경을 올바른 자바 경로를 바로볼 수 있게 설정하는 방법입니다.
이 방법 또한 성공적으로 빌드를 실행시킬 수 있었습니다. 아래 공식문서를 참고해보면 좋습니다

https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties

 

Build Environment

Gradle can also set project properties when it sees specially-named system properties or environment variables. If the environment variable name looks like ORG_GRADLE_PROJECT_prop=somevalue, then Gradle will set a prop property on your project object, with

docs.gradle.org

 

와! 빌드 성공!!

사실 삽질 진짜 많이했는데  ㅠㅠㅠ 너무 행복해

 


5. EC2 백그라운드 실행

성공적으로 jar 파일을 만들었으니 이제 터미널에서 ec2접속을 끊어도 서버가 유지되게 .jar 파일을 백그라운드 실행해야 합니다.( nohup 참고)

nohup java -jar api-0.0.1-SNAPSHOT.jar &

 

별도의 포트포워딩을 해주지 않았기 때문에 8080 포트로 접속을 하면 됩니다.

  • (연결이 안된다면 aws 인바운드 규칙으로 8080 포트 열어주기)

[퍼블릭 IPv4 주소]:8080/hello  

great!

 

 

 

 

아 java 17 은 고통이다

삽질 끝..

 

 

 


*참고

 

반응형