Skip to content

TIL -2025-05-29 [EC2 + Docker + MariaDB + Spring Boot 배포 복습, RDS 반영 (MariaDB RDS 사용하여 Spring Boot 연결), 액션즈 붙이기, Slack webhook 붙이기] #78

Description

@soheeGit

📌 EC2 + Docker + MariaDB + Spring Boot 배포 복습

1. EC2 인스턴스 생성

  • Ubuntu 22.04 LTS 선택
  • 보안 그룹에서 인바운드 규칙: SSH(22), HTTP(80), MySQL(3306) 등 필요한 포트 오픈
  • 키 페어 생성 (keykey.pem)
Image Image

2. EC2 인스턴스 접속

chmod 400 *.pem
ssh -i "keykey.pem" ubuntu@ec2-13-209-35-195.ap-northeast-2.compute.amazonaws.com
Image
  • 네트워크 확인
ping 8.8.8.8
curl ifconfig.me

3. Docker 설치 (공식 가이드 기반)

# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  • 설치 확인
docker --version
docker compose version
sudo docker run hello-world
  • sudo 없이 docker 명령어 사용
sudo gpasswd -a $USER docker
sudo service docker restart
sudo su - 
su - ubuntu # 다시 일반 계정으로 돌아가기

4. MariaDB 설치 (Docker)

docker run -d -p 3306:3306 --name db -e MARIADB_ROOT_PASSWORD=rootpass -e MARIADB_DATABASE=mydb mariadb:latest
Image

5. DBeaver 연결 실패 원인 및 해결

연결 실패 원인

  • AWS 보안 그룹에서 3306 포트가 열려있지 않음
Image Image

해결 방법

  1. EC2 대시보드 → 보안 → 보안 그룹
  2. 인바운드 규칙 → 편집
  3. 규칙 추가:
  • 유형: MySQL/Aurora
  • 포트 범위: 3306
  • 소스: 내 IP 또는 0.0.0.0/0 (공개 허용)
Image Image
  • 연결 성공!
Image

6. Spring Boot 프로젝트 (boot-cloud-step3) 빌드 및 실행

git clone https://github.com/soheeGit/boot-cloud-step3.git
cd boot-cloud-step3
docker build -t step3 .
docker run -d -p 80:8080 --name step3 -e DB_URL=jdbc:mariadb://13.209.35.195:3306/mydb -e DB_USERNAME=root -e DB_PASSWORD=rootpass step3

7. 실행 실패 - RDS로 전환

💀 죽었다.
잘가~


📌 RDS 반영 (MariaDB RDS 사용하여 Spring Boot 연결)

1. AWS RDS 인스턴스 생성

  1. AWS 콘솔 → RDS → 데이터베이스 생성
  2. 엔진 선택: MariaDB
  3. 템플릿: 프리 티어 사용 가능 선택
  4. 설정
  • DB 식별자: database-1
  • 마스터 사용자 이름: admin
  • 비밀번호: y7ZaAcFbZPqXOtYpy74O (예시, 노출주의)
  1. DB 인스턴스 옵션
  • 퍼블릭 액세스: 예 (Yes) (배포 목적이면 외부 접속 가능해야 함)
  • 가용 영역 등은 기본값 사용
  1. VPC 보안 그룹: EC2와 동일한 보안 그룹 설정
  • 인바운드 규칙: 포트 3306, 소스 EC2 IP 또는 0.0.0.0/0 (테스트 시)
Image Image Image Image Image
  • 둘만의 관계 생성
Image Image

3. 보안 강화를 위한 접근 제한 설정

  • 필요 시 RDS 인스턴스를 퍼블릭 비활성화
  • 또는 보안 그룹에서 EC2 인스턴스만 접속하도록 제한
Image

4. EC2에 Docker 설치 및 애플리케이션 배포 전체 요약

chmod 400 "keykeykey.pem"
ssh -i "keykeykey.pem" ubuntu@ec2-3-35-10-229.ap-northeast-2.compute.amazonaws.com
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  • 설치 확인
docker --version
docker compose version
sudo docker run hello-world
  • sudo 없이 docker 명령어 사용
sudo gpasswd -a $USER docker
sudo service docker restart
sudo su - 
su - ubuntu # 다시 일반 계정으로 돌아가기

5. Spring Boot 프로젝트 배포

git clone https://github.com/soheeGit/boot-cloud-step3.git
cd boot-cloud-step3
docker build -t step3 .
docker run -d -p 80:8080 --name step3 -e DB_URL=jdbc:mariadb://database-1.cxk0ssqi8ba9.ap-northeast-2.rds.amazonaws.com:3306/mydb -e DB_USERNAME=root -e DB_PASSWORD=y7ZaAcFbZPqXOtYpy74O step3
curl ifconfig.me
Image

📌 액션즈 붙이기

  • .github/workflows/ghcr.yml
name: Docker Image CI with Layer Caching

on:
  push:
    branches:
      - main

jobs:
  build-and-push:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      packages: write

    steps:
      # GitHub에 올라간 내 프로젝트 코드를 작업 환경으로 가져오기
      - name: Checkout repository
        uses: actions/checkout@v4
        # 참고: https://github.com/actions/checkout

      # Docker 환경 설정 (프로그램을 담는 컨테이너를 만드는 환경을 준비)
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        # 참고: https://github.com/docker/setup-buildx-action

      # GitHub의 저장소(컨테이너를 보관하는 공간)에 로그인
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
        # 참고: https://github.com/docker/login-action

      # Docker 이미지에 이름표(태그와 라벨)를 자동으로 붙여주는 과정
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
        # 참고: https://github.com/docker/metadata-action

      # Docker가 빠르게 작동하도록 이전 작업 내용을 기억하는 캐시 설정
      - name: Cache Docker layers
        uses: actions/cache@v4
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-
        # 참고: https://docs.github.com/actions/using-workflows/caching-dependencies-to-speed-up-workflows

      # 컨테이너 이미지(Docker 이미지)를 실제로 만들어서 저장소에 올리기
      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache
  1. main 브랜치로 push
    → GitHub Actions (.github/workflows/ghcr.yml) 동작

  2. Docker 이미지 빌드
    → Dockerfile 기준으로 GitHub Actions에서 이미지 생성

  3. 이미지를 ghcr.io에 push
    → 자동으로 ghcr.io/soheegit/boot-cloud-step3:main 저장됨

  4. EC2에서 pull + run
    → docker run ... ghcr.io/soheegit/boot-cloud-step3:main 실행

# docker rm -f step3
docker rmi ghcr.io/soheegit/boot-cloud-step3:main
docker run -d -p 80:8080 --name step3 -e DB_URL=jdbc:mariadb://database-1.cxk0ssqi8ba9.ap-northeast-2.rds.amazonaws.com:3306/mydb -e DB_USERNAME=root -e DB_PASSWORD=y7ZaAcFbZPqXOtYpy74O ghcr.io/soheegit/boot-cloud-step3:main

📌 Slack webhook 붙이기

Image Image
  • .github/workflows/ghcr.yml 수정
name: Docker Image CI with Layer Caching

on:
  push:
    branches:
      - main

jobs:
  build-and-push:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      packages: write

    steps:
      # GitHub에 올라간 내 프로젝트 코드를 작업 환경으로 가져오기
      - name: Checkout repository
        uses: actions/checkout@v4
        # 참고: https://github.com/actions/checkout

      # Docker 환경 설정 (프로그램을 담는 컨테이너를 만드는 환경을 준비)
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        # 참고: https://github.com/docker/setup-buildx-action

      # GitHub의 저장소(컨테이너를 보관하는 공간)에 로그인
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
        # 참고: https://github.com/docker/login-action

      # Docker 이미지에 이름표(태그와 라벨)를 자동으로 붙여주는 과정
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
        # 참고: https://github.com/docker/metadata-action

      # Docker가 빠르게 작동하도록 이전 작업 내용을 기억하는 캐시 설정
      - name: Cache Docker layers
        uses: actions/cache@v4
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-
        # 참고: https://docs.github.com/actions/using-workflows/caching-dependencies-to-speed-up-workflows

      # 컨테이너 이미지(Docker 이미지)를 실제로 만들어서 저장소에 올리기
      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache

      # Slack으로 결과 전송
      - name: Send Slack Notification
        if: always() # Send notification regardless of build success or failure
        uses: act10ns/slack@v2.1.0
        with:
          webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }} # Replace with your Slack webhook URL secret
          status: ${{ job.status }}
          message: |
            *GitHub Actions Workflow Status:*
            *Repository:* `${{ github.repository }}`
            *Branch:* `${{ github.ref_name }}`
            *Commit:* `${{ github.sha }}`
            *Workflow:* `${{ github.workflow }}`
            *Run ID:* `${{ github.run_id }}`
            *Status:* `${{ job.status }}`
            *Link:* `${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}`
          # You can customize the message further with more details
          # For example, if you want to show the Docker image tags:
          # `*Docker Image Tags:* ${{ steps.meta.outputs.tags }}`
Image

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions