Skip to content

Commit

Permalink
블루/그린 전략으로 배포가 이루어질 수 있는 환경을 설정한다. (#84)
Browse files Browse the repository at this point in the history
  • Loading branch information
fru1tworld authored Nov 10, 2024
2 parents ea55fc5 + 962d75e commit 2015217
Show file tree
Hide file tree
Showing 25 changed files with 9,335 additions and 11 deletions.
79 changes: 79 additions & 0 deletions .github/workflows/BACKEND_DEPLOY.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
name: 백엔드 배포
on:
push:
branches: [main]
paths:
- "packages/backend/**"
- "packages/shared/**"
jobs:
push_to_registry:
runs-on: ubuntu-latest
steps:
- name: 코드 체크아웃
uses: actions/checkout@v3

- name: Docker Buildx 설정
uses: docker/setup-buildx-action@v2

- name: NCP 컨테이너 레지스트리 로그인
uses: docker/login-action@v2
with:
registry: ${{ secrets.CONTAINER_REGISTRY_URL }}
username: ${{ secrets.NCP_ACCESS_KEY }}
password: ${{ secrets.NCP_SECERET_KEY }}

- name: 도커 이미지 빌드 및 푸시
id: docker-build
uses: docker/build-push-action@v3
with:
context: .
file: ./packages/backend/Dockerfile
push: true
tags: ${{secrets.CONTAINER_REGISTRY_URL}}/nodejs-server:latest

- name: 배포 결과 처리
if: always()
uses: actions/github-script@v6
with:
script: |
const buildOutcome = '${{ steps.docker-build.outcome }}';
const repoName = context.repo.repo;
await github.rest.checks.create({
owner: context.repo.owner,
repo: repoName,
name: '백엔드 배포 상태',
head_sha: context.sha,
status: 'completed',
conclusion: buildOutcome === 'success' ? 'success' : 'failure',
output: {
title: buildOutcome === 'success'
? '🚀 백엔드 배포 성공'
: '❌ 백엔드 배포 실패',
summary: buildOutcome === 'success'
? [
'## ✅ 배포 상태: 성공',
'',
'### 배포 정보:',
'- 📅 **배포 시간**: ' + new Date().toISOString(),
'- 🌏 **환경**: Production',
'- 📦 **이미지**: nodejs-server:latest',
'- 🎯 **대상**: NCP Container Registry',
'',
'🎉 프로덕션 환경에 성공적으로 배포되었습니다!'
].join('\n')
: [
'## ❌ 배포 상태: 실패',
'',
'### 오류 정보:',
'- 📅 **실패 시간**: ' + new Date().toISOString(),
'- 🚨 **실패 단계**: Docker 빌드 및 푸시',
'',
'### 문제 해결 방법:',
'1. Dockerfile 설정을 확인해주세요',
'2. 빌드 로그를 확인해주세요',
'3. NCP 인증 정보를 확인해주세요',
'',
].join('\n')
}
});
66 changes: 66 additions & 0 deletions .github/workflows/FRONTEND_DEPLOY.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: 프론트엔드 배포
on:
push:
branches: [main]
paths:
- "packages/frontend/**"
- "packages/shared/**"

permissions:
contents: read
checks: write
pull-requests: write

jobs:
push_to_registry:
runs-on: ubuntu-latest
steps:
- name: 코드 체크아웃
uses: actions/checkout@v3

- name: NCP 컨테이너 레지스트리 로그인
uses: docker/login-action@v2
with:
registry: ${{ secrets.CONTAINER_REGISTRY_URL }}
username: ${{ secrets.NCP_ACCESS_KEY }}
password: ${{ secrets.NCP_SECRET_KEY }}

- name: 도커 이미지 빌드 및 푸시 (Blue)
id: docker-build-blue
uses: docker/build-push-action@v3
with:
context: .
file: ./packages/frontend/Dockerfile
push: true
tags: ${{ secrets.CONTAINER_REGISTRY_URL }}/frontend:latest

pull_from_registry:
runs-on: ubuntu-latest
needs: push_to_registry
steps:
- name: SSH로 서버 접속
uses: appleboy/[email protected]
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_KEY }}
port: ${{ secrets.SERVER_SSH_PORT }}
script: |
# NCP 컨테이너 레지스트리 로그인
docker login -u ${{ secrets.NCP_ACCESS_KEY }} -p ${{ secrets.NCP_SECRET_KEY }} ${{ secrets.CONTAINER_REGISTRY_URL }}
# 새로운 이미지 pull
docker pull ${{ secrets.CONTAINER_REGISTRY_URL }}/frontend:latest
# 기존 컨테이너 중지 및 제거
docker stop frontend || true
docker rm frontend || true
# 새 컨테이너 실행
docker run -d --name frontend -p 80:80 ${{ secrets.CONTAINER_REGISTRY_URL }}/frontend:latest
# 헬스체크 (선택사항)
sleep 5
if ! curl -f http://localhost:80/health; then
echo "Warning: Health check failed after deployment"
fi
59 changes: 59 additions & 0 deletions .github/workflows/REVIEW_REQUEST_ALERT.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: BeeBot
on:
pull_request:
types: [review_request_removed]
jobs:
notify_automatically_assigned_review_request:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: 알림 전송 이력이 있는지 확인
id: check_notification
uses: actions/cache@v3
with:
path: .notifications
key: notifications-${{ github.event.pull_request.number }}

- name: 리뷰어 목록 가져오기
if: steps.check_notification.outputs.cache-hit != 'true'
id: reviewers
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const workers = JSON.parse(fs.readFileSync('.github/workflows/reviewers.json'));
const mention = context.payload.pull_request.requested_reviewers.map((user) => {
const login = user.login;
const mappedValue = workers[login];
return mappedValue ? `<@${mappedValue}>` : `No mapping found for ${login}`;
});
return mention.join(', ');
result-encoding: string

- name: 슬랙 알림 전송
if: steps.check_notification.outputs.cache-hit != 'true'
uses: slackapi/[email protected]
with:
channel-id: ${{ secrets.SLACK_CHANNEL }}
payload: |
{
"text": "[리뷰 요청] 새로운 PR이 등록되었습니다!",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "[리뷰 요청] 새로운 PR이 등록되었습니다!\n • 제목: ${{ github.event.pull_request.title }}\n • 리뷰어: ${{ steps.reviewers.outputs.result }} \n • 링크: <${{ github.event.pull_request.html_url }}|리뷰하러 가기>"
}
}
]
}
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}

- name: 알림 전송 이력 생성
if: steps.check_notification.outputs.cache-hit != 'true'
run: |
mkdir -p .notifications
touch .notifications/sent
7 changes: 7 additions & 0 deletions .github/workflows/reviewers.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"fru1tworld": "U07H6QPSEE7",
"heegenie": "U07GSBFR0Q7",
"CatyJazzy": "U07GSBRJF9D",
"parkblo": "U07H6TN3WTC",
"hoqn": "U07HKHTP2TT"
}
31 changes: 31 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.eslintcache

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

# env
.env

# develop
*/backend/docker.compose.yml
1 change: 1 addition & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pnpm dlx commitlint --edit $1
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pnpm lint-staged
11 changes: 11 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"singleQuote": false,
"tabWidth": 2,
"semi": true,
"printWidth": 80,
"arrowParens": "always",
"jsxSingleQuote": false,
"bracketSpacing": true,
"trailingComma": "all",
"jsxBracketSameLine": false
}
3 changes: 3 additions & 0 deletions commitlint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
extends: ["@commitlint/config-conventional"],
};
43 changes: 43 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* eslint-disable no-underscore-dangle */
import pluginJs from "@eslint/js";
import prettierConfig from "eslint-config-prettier";
import prettierPluginRecommended from "eslint-plugin-prettier/recommended";
import tseslint from "typescript-eslint";

/** @see https://www.raulmelo.me/en/blog/migration-eslint-to-flat-config */
import { FlatCompat } from "@eslint/eslintrc";
import path from "path";
import { fileURLToPath } from "url";
// mimic CommonJS variables -- not needed if using CommonJS
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname, // optional
});

/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["**/*.{js,mjs,cjs,ts}"] },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...compat.extends("airbnb-base"),
prettierConfig,
prettierPluginRecommended,
{
rules: {
"import/no-extraneous-dependencies": [
"warn",
{
devDependencies: [
"**/*.config.{mts,ts,mjs,js}",
"**/storybook/**",
"**/stories/**",
"**/*.stories.{ts,tsx,js,jsx}",
"**/*.{spec,test}.{ts,tsx,js,jsx}",
],
},
],
},
},
];
29 changes: 27 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,34 @@
"description": "",
"private": "true",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"lint": "eslint --filter \"frontend,backend\" lint",
"test": "echo \"Error: no test specified\" && exit 1",
"prepare": "husky"
},
"keywords": [],
"author": "",
"license": "MIT"
"license": "MIT",
"devDependencies": {
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"eslint": "^9.14.0",
"eslint-plugin-import": "^2.31.0",
"husky": "^9.1.6",
"lint-staged": "^15.2.10",
"prettier": "3.3.3",
"typescript": "^5.6.3",
"typescript-eslint": "^8.13.0",
"@eslint/eslintrc": "^3.1.0",
"@eslint/js": "^9.14.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1"
},
"dependencies": {},
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"eslint --cache --fix",
"prettier --cache --write"
]
}
}
8 changes: 7 additions & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,15 @@
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/mongoose": "^10.1.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^10.0.2",
"ioredis": "^5.4.1",
"mongoose": "^8.8.0",
"mysql2": "^3.11.4",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand Down
5 changes: 4 additions & 1 deletion packages/backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ContextModule } from './context/context.module';
import { ChaceModule } from './chace/chace.module';
import { ContentModule } from './content/content.module';

@Module({
imports: [],
imports: [ContextModule, ChaceModule, ContentModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
7 changes: 7 additions & 0 deletions packages/backend/src/chace/chace.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { ChaceService } from './chace.service';

@Module({
providers: [ChaceService]
})
export class ChaceModule {}
Loading

0 comments on commit 2015217

Please sign in to comment.