Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] DB 세팅 및 배포 플로우 자동화 기본 작업 #5

Merged
merged 5 commits into from
Feb 5, 2025

Conversation

Lim-Changi
Copy link
Member

@Lim-Changi Lim-Changi commented Feb 1, 2025

관련 이슈가 있다면 적어주세요.

issue #2

📌 개발 이유

기본적인 원격 환경 배포에 필요한 리소스들 세팅 작업

💻 수정 사항

  • Resource 환경변수 .env 로 관리되도록 작업 ( env 파일은 따로 전달예정 )
    • Docker 이미지가 빌드될 때, 환경변수가 포함되지 않도록 하기 위함
    • 이미지를 컨테이너로 띄울 때 외부 .env 파일에서 환경변수를 읽어오는 구조
    • Dev, Prod 환경 분리지어 env 생성 ⇒ Spring Profile 통해서 분리 dev/prod
    • Intellij 로컬 빌드 시 .env 설정 방법
프로젝트 루트 디렉토리에서 .env 파일 생성
Run Configuration 설정
상단 메뉴에서 'Edit Configurations' 클릭
실행하려는 애플리케이션의 구성 선택 (Spring Boot 구성)

'Environment' 섹션에서:
'EnvFile' 탭 클릭
'+' 버튼을 눌러 'Add EnvFile' 선택
생성한 .env 파일 경로 선택
'Enable EnvFile' 체크박스 선택
  • MySQL 세팅

    • AWS MySQL RDS 생성
    • MySQL 드라이버 추가
    • DB 관련 환경변수 추가 datasource, jpa
    • 로컬에서도 Dev RDS 접근하여 작업하는 구조
      • 현재는 Dev Schema 만 생성 (development)
  • 도커 세팅

    • Dockerfile 빌드 단계와 실행 단계 분리 (Multi Stage Build)
      • 관련 공식 문서 ⇒ 링크
    • 로컬에서 빌드 테스트할 수 있도록 docker compose 파일 생성
      • 명령어
      • Docker Engine 버전 < 20.10.13 ⇒ docker-compose up --build
      • 최신 버전 ⇒ docker compose up --build
    • 실제 배포할 때에는 compose 파일 활용 X (명령어로 처리)
      • 추가 컨테이너 리소스 발생 시, Compose 로 배포하는 방향 고민
  • GitAction 기반 자동 배포 CD Flow

    • 사전 작업
      • EC2 인스턴스 생성
      • 인스턴스에 aws cli 및 configuration 설정,
      • docker 다운로드
    • 빌드 단계
      • AWS 로그인
      • 이미지 빌드
      • AWS Public ECR Repo 이미지 push
    • 배포 단계
      • Dev 인스턴스에 Host 정보와 PEM 키 활용하여 SSH 로그인
      • 기존 컨테이너 내리고 삭제
      • 이전 이미지 삭제 (새 배포 이미지를 위한 메모리 확보)
      • Public ECR 에서 새 이미지 pull
      • 도커 명령어로 8080 port 에서 컨테이너 실행

🎯 리뷰 포인트

  • 궁금하신 부분은 편하게 다 물어봐주세용

@Lim-Changi Lim-Changi added 🚀 Deploy 배포 관련 ✨ Feature 기능 추가 구현 labels Feb 1, 2025
@Lim-Changi Lim-Changi self-assigned this Feb 1, 2025
Copy link

coderabbitai bot commented Feb 1, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@helenason helenason changed the title [Feat]: DB 세팅 및 배포 플로우 자동화 기본 작업 [Feat] DB 세팅 및 배포 플로우 자동화 기본 작업 Feb 2, 2025
Copy link
Collaborator

@helenason helenason left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

인프라 작업 진행하시느라 너무 수고 많으셨습니다. 제가 인프라 지식이 부족하여 몇가지 질문하고 싶은 게 있어요!

MySQL 세팅 관련

  1. "로컬에서도 Dev RDS 접근하여 작업하는 구조"라는 것이, 로컬 Application을 실행할 때는 dev RDS에 접근하도록 하고, 로컬 테스트를 실행할 때는 경호님이 구축한 테스트 컨테이너를 활용하는 것이 맞는지 궁금해요!

도커 세팅 관련

  1. "Dockerfile 빌드 단계와 실행 단계 분리"한 목적이 무엇인지 궁금합니다! 검색해 보았을 때 여러 목적이 언급되었는데 그중에서도 찬기님이 생각하시는 이유가 궁금해요!
  2. "로컬에서 빌드 테스트할 수 있도록 docker compose 파일 생성"을 해주셨는데, 로컬에서 빌드 테스트를 하는 이유는 배포 전 문제를 사전에 발견하고 안정적으로 배포하기 위함이라고 봐도 될까요?! 로컬에서 빌드 테스트를 해본 경험이 없어 질문 드려요.

CD Flow 관련

  1. "AWS Public ECR Repo"가 어떤 목적으로 도입되었는지 궁금해요! Dockerhub와 비슷한 역할(빌드된 이미지를 저장하는 용도)을 한다고 봐도 될까요?!

궁금하신 부분은 편하게 모두 물어봐도 된다고 하셔서 제가 이해한 방향이 맞는지 헷갈리는 모든 것을 질문하였습니다.. 감사합니다!

+) 그리고 곳곳에 추가되지 않은 EOL(맨 밑 개행) 추가해주시면 정말 감사하겠습니다 🙇‍♀️🥹

Copy link
Member

@Hoya324 Hoya324 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수고하셨습니다!!
멀티 스테이지 부분의 이점이 이미지 크기가 작아지는 것만으로 좋아보이고, 보안상 좋다고 하는데 도입이 이유가 이게 맞는건지 궁금합니다! 이 부분은 채영님이 잘 정리해서 질문해주셔서 같이 답해주시면 될거 같아요!

@Lim-Changi
Copy link
Member Author

MySQL 세팅

"로컬에서도 Dev RDS 접근하여 작업하는 구조"라는 것이, 로컬 Application을 실행할 때는 dev RDS에 접근하도록 하고, 로컬 테스트를 실행할 때는 경호님이 구축한 테스트 컨테이너를 활용하는 것이 맞는지 궁금해요!

넵넵 정확히 말씀주신대로,

  • 로컬에서 Application 을 실행할 때에는, Dev RDS 에 접근하여 Dev 서버와 동일한 DB 를 바라보고 서버가 실행됩니다
  • 로컬 Test 및 CI Flow 에서 Test 를 돌릴때는, 경호님이 구축해주신 H2 인메모리 DB가 새로 띄워지고 테스트 데이터가 들어간 후에, 테스트가 종료되면 삭제되어 초기화되는 구조입니다 (제가 이해한게 맞..죠..? @Hoya324 )

Docker 세팅

"Dockerfile 빌드 단계와 실행 단계 분리"한 목적이 무엇인지 궁금합니다! 검색해 보았을 때 여러 목적이 언급되었는데 그중에서도 찬기님이 생각하시는 이유가 궁금해요!

가장 큰 목적은 이미지 사이즈 최적화 입니다.

저희 로컬과 다르게 EC2 인스턴스는 용량(EBS)이 제한적이어서, 저희가 만약 메인 서비스 Application 이외에 추가 서버나 툴을 도커로 관리한다고 하면 이미지 저장 용량이 금방 꽉차게 됩니다. (⇒ 새 이미지를 배포할 때는 이전 배포 이미지를 항상 삭제함)

따라서 배포에 꼭 필요한 부분만 가져와서 이미지 크기를 줄이는 Multi Stage Build 는 필수적이고, 이미지 크기가 줄어듦에 따라 배포 시간이 단축된다는 장점도 있습니다.
Auto Scaling 설정이 걸려있는 경우, 배포 시간이 단축됨에 따라 더 빠르게 Scale out 이 가능하여 트래픽이 급증하는 경우에 더 빠른 속도로 대처가 가능합니다.


추가로 보안측면에서는,

  • 빌드되기 전 원천 소스코드가 배포 이미지에 포함되지 않는다는 점 == 컴파일된 바이너리코드만 배포파일에 포함됨
    • 사실 사프라서 공개 Repo 로 관리되다 보니, 현재 프로젝트에는 크게 상관은 없지만 Private 레포에서 작업되는 경우 오픈된 공간에 잘못 이미지를 배포하게 되면 치명적일 수 있습니다.
  • 빌드 도구(Maven/Gradle 등)이 최종 이미지에서 제거 됨에 따라 빌드 도구의 취약점을 활용한 공격을 차단할 수 있습니다..라고 하는데 사실 이 부분은 저도 특별히 SpringBoot 에서는 아는바가 없어 GPT 에게 물어봤습니다.
Gradle Wrapper 취약점 공격

# 공격자가 컨테이너에 접근하여 실행 가능한 wrapper 발견
$ find / -name "gradlew"
/app/gradlew

# wrapper.jar를 통한 임의 코드 실행
# CVE-2020-11979: Gradle Wrapper 취약점 사례
$ ./gradlew --stop    # 기존 데몬 중지
$ ./gradlew -Dorg.gradle.jvmargs="-agentlib:jdwp=transport=dt_socket,server=y,suspend


의존성 하이재킹(Dependency Hijacking)

// 프로덕션에 남은 build.gradle
repositories {
    mavenCentral()
    // 안전하지 않은 저장소
    maven { url "http://insecure-repo.com" }
}

# 공격자가 의존성을 조작하여 악성 코드 주입
$ ./gradlew --refresh-dependencies


플러그인 설정 악용
<!-- 남은 Maven 설정 파일의 취약한 플러그인 설정 -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <configuration>
        <executable>bash</executable>
        <arguments>
            <argument>-c</argument>
            <argument>echo "Sensitive command execution"</argument>
        </arguments>
    </configuration>
</plugin>

# 공격자가 플러그인 실행을 통해 임의 명령 실행
$ mvn exec:exec

"로컬에서 빌드 테스트할 수 있도록 docker compose 파일 생성"을 해주셨는데, 로컬에서 빌드 테스트를 하는 이유는 배포 전 문제를 사전에 발견하고 안정적으로 배포하기 위함이라고 봐도 될까요?! 로컬에서 빌드 테스트를 해본 경험이 없어 질문 드려요.

네네 일반적으로 로컬에서 Application 을 실행하는 환경과 도커환경에서 실행하는 환경이 많이 달라서, 배포하기 전에 확인하는 용도로 사용됩니다.
추가 이미지 리소스(ex. Redis) 가 쓰이는 경우, compose 에서 추가하고 어플리케이션 이미지와 잘 연동이 되는지 테스트도 진행 해볼 수 있습니다!

CD Flow

"AWS Public ECR Repo"가 어떤 목적으로 도입되었는지 궁금해요! Dockerhub와 비슷한 역할(빌드된 이미지를 저장하는 용도)을 한다고 봐도 될까요?!

넵! DockerHub 과 동일하다고 생각해주시면 될 것 같습니다.
다만 차이가 있다면 DockerHub 의 경우,

  • 한명의 작업자 도커 계정에 종속되는 문제가 있고 (생각해보니 생성한 구글계정으로 해도 됐을지도?)
  • AWS Public ECR Repo 보다 더 쉽게 공개되어 있는 환경입니다.

Private ECR Repo 를 사용하면 더 좋았겠지만, 프리티어 상에서 이미지 용량 제한이 너무 작고 비용적인 문제가 있어 Public Repo 를 사용하게 되었습니다.

Public Repo의 경우 AWS Configure 을 하지 않아도 Pull 이 가능하지만, configure 설정 후 pull 하게 되면 ECR 사용량이 덜 제한적이게 되어 IAM Key 설정을 해두는 것이 좋습니다.

@Lim-Changi
Copy link
Member Author

EOL 작업 완!

@Hoya324
Copy link
Member

Hoya324 commented Feb 4, 2025

  • 로컬에서 Application 을 실행할 때에는, Dev RDS 에 접근하여 Dev 서버와 동일한 DB 를 바라보고 서버가 실행됩니다
  • 로컬 Test 및 CI Flow 에서 Test 를 돌릴때는, 경호님이 구축해주신 H2 인메모리 DB가 새로 띄워지고 테스트 데이터가 들어간 후에, 테스트가 종료되면 삭제되어 초기화되는 구조입니다 (제가 이해한게 맞..죠..? @Hoya324 )

H2 대신 저희가 사용하기로 한 MySQL을 기존의 H2를 인메모리에서 사용했던 것처럼 docker가 자동으로 올라갔다가 사라진는 구조입니다! 플로우 자체는 이해하신게 맞아요!!

@Lim-Changi Lim-Changi merged commit d15527f into feat/2-initial-setup Feb 5, 2025
1 check passed
@Lim-Changi Lim-Changi deleted the feat/2-infra-setup branch February 5, 2025 00:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🚀 Deploy 배포 관련 ✨ Feature 기능 추가 구현
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants