Skip to content
This repository was archived by the owner on Mar 7, 2026. It is now read-only.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📘 인터뷰 기반 자서전 생성 시스템 API

Interactive interview system for generating autobiographies through AI-powered conversations.

🚀 Quick Start

⚡ Quick Setup (Recommended)

# 1. AWS CLI 설정 (처음 한 번만)
aws configure

# 2. 자동 설정 스크립트 실행 (.env에서 기존 값 자동 로드)
./setup-config.sh

# 3. 초기 배포
./deploy.sh

# 4. 코드 수정 후 재배포 (.env에서 자동으로 설정 로드)
./redeploy.sh

🎯 핵심 특징:

  • .env 파일에서 기존 설정 자동 로드
  • ✅ 변경이 필요한 값만 입력 요청
  • ✅ 모든 스크립트가 .env에서 설정 자동 읽기

Local Development

# Install dependencies
npm install

# Copy environment file
cp .env.example .env

# Edit .env with your configuration
# Start development server
npm run dev

# Test the API
./test-api.sh

AWS Deployment

# Initial deployment
./deploy.sh

# Code updates (after making changes)
./redeploy.sh

# Test deployed API
./test-api.sh http://{public-ip}:3000/api/v2

📊 Current Deployment Info

🖥️ Server Details

  • EC2 IP: {public-ip}
  • SSH Access: ssh -i server.pem ec2-user@{public-ip}
  • API URL: http://{public-ip}:3000
  • Swagger UI: http://{public-ip}:3000/api/v2/docs

🗄️ Database Details

  • Type: MariaDB (Local on EC2)
  • Host: localhost (from EC2)
  • Port: 3306
  • Database: autobiography_db
  • User: root
  • Password: your-secure-password
  • Connection: SSH to EC2 required

📁 Project Files

  • setup-config.sh - Automatic configuration setup
  • deploy.sh - Initial AWS deployment
  • redeploy.sh - Code update deployment
  • infra.yaml - CloudFormation template
  • server.pem - EC2 SSH key
  • test-api.sh - API testing script

🔐 보안 설정 및 민감 정보 관리

📋 민감 정보 목록

이 프로젝트에서 관리해야 할 민감한 정보들:

  • AWS Account ID: CloudFormation, ECR 등에서 사용
  • EC2 Public IP: 서버 접속 및 API 엔드포인트
  • SSH Private Key: EC2 서버 접속용 (server.pem)
  • Database Password: MariaDB 접속 비밀번호
  • AWS Credentials: Bedrock, S3 접근용

🛡️ 보안 설정 방법

1. AWS 계정 설정

# AWS CLI 설정 (처음 한 번만)
aws configure
# AWS Access Key ID: [Your Access Key]
# AWS Secret Access Key: [Your Secret Key]
# Default region name: ap-northeast-2
# Default output format: json

# 계정 ID 확인
aws sts get-caller-identity --query Account --output text

2. 환경 변수 설정

# .env 파일 생성 및 편집
cp .env.example .env
vim .env

# 다음 값들을 실제 값으로 변경:
# - AWS_REGION=ap-northeast-2
# - S3_BUCKET_NAME={project-name}-images-{your-aws-account-id}
# - DB_PASSWORD=your-secure-password

3. 배포 스크립트 설정

# deploy.sh와 redeploy.sh에서 다음 변수들을 실제 값으로 변경:
# - ACCOUNT_ID: AWS 계정 ID
# - REGION: AWS 리전 (ap-northeast-2)
# - ECR_URI: {your-aws-account-id}.dkr.ecr.{your-region}.amazonaws.com/{project-name}

4. CloudFormation 템플릿 설정

# infra.yaml에서 다음 값들을 확인/수정:
# - S3 버킷 이름: {project-name}-images-{your-aws-account-id}
# - 프로젝트 이름: autobiography-api (또는 원하는 이름)

🔑 SSH 키 관리

1. 새 SSH 키 생성 (선택사항)

# 새 키 페어 생성
aws ec2 create-key-pair --key-name {your-key-name} --region {your-region} \
  --query 'KeyMaterial' --output text > {your-key-name}.pem

# 권한 설정
chmod 400 {your-key-name}.pem

2. 기존 키 사용

# 기존 server.pem 파일의 권한 확인
chmod 400 server.pem

# SSH 연결 테스트
ssh -i server.pem ec2-user@{your-ec2-ip} 'echo "Connection successful"'

🗄️ 데이터베이스 보안

1. 비밀번호 변경

# EC2에 접속
ssh -i server.pem ec2-user@{your-ec2-ip}

# MariaDB 비밀번호 변경
sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'your-new-secure-password';"

# .env 파일 업데이트
vim /home/ec2-user/app/.env
# DB_PASSWORD=your-new-secure-password

2. 데이터베이스 백업 암호화

# 암호화된 백업 생성
mysqldump -u root -p{password} autobiography_db | gzip | gpg --symmetric --cipher-algo AES256 > backup_$(date +%Y%m%d).sql.gz.gpg

🌐 네트워크 보안

1. Security Group 설정

# 현재 IP만 SSH 접근 허용
MY_IP=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress \
  --group-id {security-group-id} \
  --protocol tcp \
  --port 22 \
  --cidr ${MY_IP}/32

2. HTTPS 설정 (권장)

# Let's Encrypt SSL 인증서 설치
ssh -i server.pem ec2-user@{your-ec2-ip}
sudo yum install -y certbot
sudo certbot certonly --standalone -d {your-domain.com}

# Nginx 리버스 프록시 설정
sudo yum install -y nginx
# nginx.conf 설정 후 SSL 적용

📊 모니터링 및 알림

1. CloudWatch 알람 설정

# CPU 사용률 알람
aws cloudwatch put-metric-alarm \
  --alarm-name "EC2-HighCPU" \
  --alarm-description "EC2 CPU usage over 80%" \
  --metric-name CPUUtilization \
  --namespace AWS/EC2 \
  --statistic Average \
  --period 300 \
  --threshold 80 \
  --comparison-operator GreaterThanThreshold \
  --dimensions Name=InstanceId,Value={your-instance-id} \
  --evaluation-periods 2

2. 로그 모니터링

# 애플리케이션 로그 실시간 모니터링
ssh -i server.pem ec2-user@{your-ec2-ip}
docker logs autobiography-api -f | grep -E "(ERROR|WARN|Failed)"

🔄 정기 보안 점검

1. 시스템 업데이트 (월 1회)

ssh -i server.pem ec2-user@{your-ec2-ip}
sudo yum update -y
docker system prune -f

2. 접근 로그 확인 (주 1회)

# SSH 접근 로그 확인
sudo journalctl -u sshd --since "1 week ago" | grep "Accepted\|Failed"

# 애플리케이션 접근 로그 확인
docker logs autobiography-api --since 168h | grep -E "POST|GET" | tail -100

3. 백업 확인 (일 1회)

# 자동 백업 스크립트 생성
cat > /home/ec2-user/backup.sh << 'EOF'
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
mysqldump -u root -p{password} autobiography_db > /home/ec2-user/backups/backup_${DATE}.sql
find /home/ec2-user/backups -name "backup_*.sql" -mtime +7 -delete
EOF

chmod +x /home/ec2-user/backup.sh

# Cron 작업 추가
echo "0 2 * * * /home/ec2-user/backup.sh" | crontab -

⚠️ 보안 주의사항

1. 절대 공개하면 안 되는 정보

  • AWS Access Key / Secret Key
  • EC2 Private Key (.pem 파일)
  • 데이터베이스 비밀번호
  • API 엔드포인트 (운영 환경)
  • AWS Account ID

2. Git 저장소 관리

# .gitignore 확인
cat .gitignore

# 민감한 파일들이 포함되어 있는지 확인:
# *.pem
# .env
# aws-credentials.json
# *.log

3. 환경 분리

# 개발/운영 환경 분리
# - 개발: .env.development
# - 운영: .env.production
# - 테스트: .env.test

# 환경별 배포 스크립트 분리
# - deploy-dev.sh
# - deploy-prod.sh

🔄 Development Workflow

Making Code Changes

  1. Edit your code in src/
  2. Run ./redeploy.sh to deploy changes
  3. Test with ./test-api.sh http://{public-ip}:3000/api/v2

Database Access

# SSH to server
ssh -i {key.pem} ec2-user@{public-ip}

# Access MariaDB
mysql -u root -ppassword123

# Use database
USE autobiography_db;
SHOW TABLES;

🛠️ 프로젝트 실행 및 유지보수 가이드

📋 프로젝트 개요

이 프로젝트는 AI 기반 인터뷰를 통해 자서전을 생성하는 RESTful API 서버입니다.

  • 8개 챕터 구조로 체계적인 인터뷰 진행
  • WebSocket 실시간 통신으로 인터뷰 상태 업데이트
  • AWS Bedrock Claude 3 AI 모델 활용
  • Docker 컨테이너 기반 배포

🚀 로컬 개발 환경 설정

1. 환경 준비

# Node.js 18+ 설치 확인
node --version

# 프로젝트 클론 후 의존성 설치
npm install

# 환경 변수 설정
cp .env.example .env
# .env 파일을 열어 데이터베이스 및 AWS 설정 입력

2. 데이터베이스 설정 (로컬)

# MariaDB/MySQL 설치 및 실행
# macOS
brew install mariadb
brew services start mariadb

# 데이터베이스 생성
mysql -u root -e "CREATE DATABASE autobiography_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

3. 개발 서버 실행

# TypeScript 컴파일 및 서버 시작
npm run dev

# 또는 빌드 후 실행
npm run build
npm start

4. API 테스트

# 로컬 API 테스트
./test-api.sh

# Health check
curl http://localhost:3000/health

# Swagger UI 접속
open http://localhost:3000/api/v2/docs

🌐 AWS 배포 및 운영

1. 초기 배포

# AWS CLI 설정 확인
aws configure list

# 초기 인프라 배포 (EC2, ECR, S3 생성)
./deploy.sh

2. 코드 업데이트 배포

# 코드 수정 후 재배포 (가장 자주 사용)
./redeploy.sh

# 수동 배포 과정 (참고용)
npm run build                    # TypeScript 빌드
docker build --platform linux/amd64 -t autobiography-api .  # Docker 이미지 빌드
docker tag autobiography-api:latest {aws_id}.dkr.ecr.ap-northeast-2.amazonaws.com/autobiography-api:latest
docker push {your-aws-account-id}.dkr.ecr.ap-northeast-2.amazonaws.com/autobiography-api:latest  # ECR 푸시
# EC2에서 컨테이너 재시작

3. 서버 상태 모니터링

# 서버 접속
ssh -i {key.pem} ec2-user@{public-ip}

# 컨테이너 상태 확인
docker ps
docker logs autobiography-api

# 시스템 리소스 확인
htop
df -h

# 데이터베이스 상태 확인
sudo systemctl status mariadb
mysql -u root -ppassword123 -e "SHOW PROCESSLIST;"

🔧 유지보수 작업

1. 로그 관리

# 애플리케이션 로그 확인
ssh -i {key.pem} ec2-user@{public-ip}
docker logs autobiography-api --tail 100 -f

# 시스템 로그 확인
sudo journalctl -u docker -f
sudo journalctl -u mariadb -f

2. 데이터베이스 백업

# 데이터베이스 백업
ssh -i {key.pem} ec2-user@{public-ip}
mysqldump -u root -ppassword123 autobiography_db > backup_$(date +%Y%m%d_%H%M%S).sql

# 백업 파일 로컬로 다운로드
scp -i {key.pem} ec2-user@{public-ip}:~/backup_*.sql ./backups/

3. 보안 업데이트

# EC2 시스템 업데이트
ssh -i {key.pem} ec2-user@{public-ip}
sudo yum update -y

# Docker 이미지 업데이트 (베이스 이미지 보안 패치)
./redeploy.sh

4. 성능 모니터링

# API 응답 시간 테스트
./test-api.sh http://{public-ip}:3000/api/v2

# 데이터베이스 성능 확인
ssh -i {key.pem} ec2-user@{public-ip}
mysql -u root -ppassword123 -e "SHOW FULL PROCESSLIST;"
mysql -u root -ppassword123 -e "SHOW ENGINE INNODB STATUS\G"

🚨 트러블슈팅

1. 서비스 재시작

# 컨테이너 재시작
ssh -i {key.pem} ec2-user@{public-ip}
docker restart autobiography-api

# 전체 재배포
./redeploy.sh

2. 데이터베이스 문제 해결

# MariaDB 재시작
ssh -i {key.pem} ec2-user@{public-ip}
sudo systemctl restart mariadb

# 데이터베이스 연결 테스트
mysql -u root -ppassword123 -e "SELECT 1;"

3. 디스크 공간 정리

# Docker 이미지 정리
ssh -i {key.pem} ec2-user@{public-ip}
docker system prune -a

# 로그 파일 정리
sudo journalctl --vacuum-time=7d

📈 확장 및 최적화

1. 성능 최적화

  • 데이터베이스 인덱스 추가
  • Redis 캐싱 도입 고려
  • CDN 적용 (정적 파일)
  • 로드 밸런서 추가 (트래픽 증가 시)

2. 보안 강화

  • HTTPS 적용 (Let's Encrypt)
  • WAF 설정
  • VPC 내부 통신으로 변경
  • Secrets Manager 활용

3. 모니터링 강화

  • CloudWatch 메트릭 설정
  • 알람 설정 (CPU, 메모리, 디스크)
  • 로그 집중화 (CloudWatch Logs)

💡 개발 팁

1. 효율적인 개발

# 코드 변경 후 빠른 테스트
npm run build && npm start

# API 엔드포인트 개별 테스트
curl -X POST http://localhost:3000/api/v2/auth/device-id-register \
  -H "Content-Type: application/json" \
  -d '{"device_id": "test-device"}'

2. 디버깅

# TypeScript 컴파일 에러 확인
npm run build

# 런타임 에러 확인
docker logs autobiography-api --tail 50

3. 환경별 설정 관리

  • 로컬: .env 파일 사용
  • 개발: EC2 환경 변수 파일
  • 운영: AWS Secrets Manager 권장

📋 API Overview

Core Flow

  1. 회원가입/로그인 → Device ID 등록
  2. 프로필 설정 → 사용자 메타데이터
  3. 챕터 시작 → WebSocket으로 첫 질문 수신
  4. 인터뷰 진행 → 답변 전송 ↔ 다음 질문 수신
  5. 상태 변화 → WebSocket으로 실시간 알림
  6. 자서전 생성 → AI가 자동 생성
  7. 책 완성 → 모든 챕터 통합

8개 챕터 구조

번호 제목 주제 설명
1 성장과정 출생, 유년기 어린 시절 환경과 기억
2 가족관계 부모, 형제, 조부모 가족 구성원과의 관계
3 학창시절 학교, 과목, 친구 학업과 친구들 이야기
4 직업/진로 직업경험, 선택이유 커리어와 직업 선택
5 가치관/성격 자아, 성격, 철학 개인의 가치관과 철학
6 인생 경험 사건, 전환점, 어려움 중요한 인생 경험들
7 감정/취향 좋아하는 것, 감정 개인적 취향과 감정
8 사회/문화 종교, 여행, 시대상 사회적 경험과 문화

🔌 API Endpoints

Authentication

POST /api/v2/auth/device-id-register
Content-Type: application/json

{
  "device_id": "unique-device-identifier"
}

User Management

POST /api/v2/user/metadata
Content-Type: application/json

{
  "user_id": "user-uuid",
  "age_group": "ADULT",
  "education_level": "UNIVERSITY_GRADUATE",
  "gender": "NONE",
  "marital_status": "SINGLE"
}

Conversation (핵심 API)

POST /api/v2/conversation/{chapter_id}
Content-Type: application/json

{
  "user_id": "user-uuid",
  "message": "저는 어린 시절에 강가에서 뛰어놀던 기억이 가장 인상 깊어요."
}

🔌 WebSocket Events

Connect to: ws://{your-ec2-ip}:3000/ws?userId={user_id}

Event Types

  • chapter_selected - 챕터 진입/이동
  • topic_updated - 주제 키워드 추출
  • interview_sufficient - 인터뷰 충분 판정
  • chapter_autobiography_generated - 자서전 생성 완료
  • chapter_completed - 챕터 종료

🏗️ Architecture

Tech Stack

  • Backend: Node.js + TypeScript + Express
  • Database: MariaDB (Local on EC2)
  • AI: AWS Bedrock (Claude 3 Sonnet)
  • Storage: AWS S3
  • WebSocket: ws library
  • Deployment: AWS EC2 + Docker + ECR

Project Structure

src/
├── config/
│   ├── database.ts          # Database configuration
│   └── swagger.ts           # API documentation
├── services/
│   ├── ai.ts               # AI service (Bedrock)
│   ├── database.ts         # Database operations
│   └── websocket.ts        # WebSocket management
├── routes/
│   └── api.ts              # All API routes (unified)
├── types/
│   └── index.ts            # TypeScript definitions
└── index.ts                # Main application

💰 Cost Optimization

Current Setup

  • EC2 t3.micro: ~$8-10/month (free tier eligible)
  • Local MariaDB: $0 (no RDS costs)
  • S3: ~$1-2/month
  • ECR: ~$0 (free tier)
  • Total: ~$10-15/month

🧪 Testing

Health Check

curl http://{public-ip}:3000/health

API Testing

# Local testing
./test-api.sh

# Production testing
./test-api.sh http://{public-ip}:3000/api/v2

🔧 Configuration

📋 Required Environment Variables

Variable Description Example How to Get
AWS_REGION AWS Region ap-northeast-2 aws configure get region
DB_PASSWORD MariaDB root password your-secure-password Choose a strong password
S3_BUCKET_NAME S3 bucket for images autobiography-api-images-123456789012 Auto-generated
ECR_REPOSITORY_URI Docker image repository 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com/autobiography-api Auto-generated

🚀 Automatic Configuration (Recommended)

# Run this once to configure everything
./setup-config.sh

This script will:

  • ✅ Detect your AWS Account ID automatically
  • ✅ Ask for your EC2 IP address
  • ✅ Ask for a secure database password
  • ✅ Generate all required variables
  • ✅ Update all configuration files

📝 Manual Configuration

# 1. Copy environment template
cp .env.example .env

# 2. Edit .env file with your values
vim .env

# 3. Update deployment scripts
# Edit redeploy.sh and replace:
# - {your-ec2-ip} with your actual EC2 IP
# - {your-aws-account-id} with your AWS Account ID

Environment Variables Details

# Server Configuration
PORT=3000
NODE_ENV=production

# Database (Local MariaDB on EC2)
DB_HOST=localhost
DB_PORT=3306
DB_NAME=autobiography_db
DB_USER=root
DB_PASSWORD=your-secure-password

# AWS Configuration
AWS_REGION=ap-northeast-2
S3_BUCKET_NAME=autobiography-api-images-{your-aws-account-id}
BEDROCK_MODEL_ID=anthropic.claude-3-sonnet-20240229-v1:0
ECR_REPOSITORY_URI={your-aws-account-id}.dkr.ecr.{your-region}.amazonaws.com/autobiography-api

📄 License

MIT License


🎯 Ready to develop?

  1. Make your code changes
  2. Run ./redeploy.sh
  3. Test at http://{public-ip}:3000/api/v2/docs

About

iot 대회용 샘플 서버

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages