MyZubster 백엔드: 전체 설정 및 배포 가이드
요약
오픈 소스 P2P 기술 공유 플랫폼인 MyZubster 백엔드의 설정 및 배포를 위한 종합 가이드입니다. Node.js, MongoDB, DeepSeek AI API를 활용한 환경 구축 방법을 다룹니다.
핵심 포인트
- Node.js와 MongoDB 기반의 백엔드 환경 설정 방법 안내
- DeepSeek AI API를 활용한 서비스 연동 설정
- Monero(XMR) 결제 시스템을 위한 환경 변수 구성
- 로컬 개발 환경부터 VPS 프로덕션 배포까지의 단계별 가이드
🚀 MyZubster 백엔드: 전체 설정 및 배포 가이드
MyZubster 백엔드를 설정, 개발 및 배포하기 위한 종합 가이드
📋 목차
프로젝트 개요 (Project Overview)
사전 요구 사항 (Prerequisites)
...
📖 프로젝트 개요 (Project Overview)
MyZubster는 이웃들이 Monero (XMR) 결제를 통해 서비스를 교환할 수 있도록 연결하는 오픈 소스 P2P (peer-to-peer) 기술 공유 플랫폼입니다. 백엔드는 다음과 같이 구축되었습니다:
Express를 사용한 Node.js (v20+)
Mongoose ODM을 사용한 MongoDB
...
🛠️ 사전 요구 사항 (Prerequisites)
로컬 머신 환경:
Node.js v20+ 설치됨
MongoDB 설치 및 실행 중
...
VPS 환경:
Linux 서버 (Ubuntu 22.04 LTS 권장)
Root 권한 또는 sudo 권한
...
💻 1. 로컬 개발 설정 (Local Development Setup)
1.1 저장소 복제 (Clone the Repository)
bash
git clone https://github.com/DanielIoni-creator/MyZubsterGateway.git
cd MyZubsterGateway
1.2 의존성 설치 (Install Dependencies)
bash
npm install
1.3 .env 파일 생성 (Create the .env File)
bash
cp .env.example .env
또는 수동으로 생성
nano .env
다음 변수들을 추가하세요:
env
PORT=3000
MONGODB_URI=mongodb://localhost:27017/myzubster
JWT_SECRET=your_super_secret_key_here
NODE_ENV=development
DeepSeek AI
DEEPSEEK_API_KEY=your_deepseek_api_key
DEEPSEEK_MODEL=deepseek-chat
DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions
Monero (추후 사용)
MONERO_RPC_URL=http://localhost:18082/json_rpc
MONERO_WALLET_ADDRESS=
MONERO_VIEW_KEY=
MONERO_NETWORK=testnet
결제 모드 (mock | real)
PAYMENT_MODE=mock
1.4 MongoDB 시작 (Start MongoDB)
bash
Ubuntu/Debian에서
sudo systemctl start mongodb
macOS에서
brew services start mongodb-community
Windows에서 (관리자 권한으로)
net start MongoDB
1.5 서버 시작 (Start the Server)
bash
node server.js
서버는 http://localhost:3000에서 시작되어야 합니다. 다음으로 테스트하세요:
bash
curl http://localhost:3000/api/health
예상 응답:
json
{
"status": "OK",
"message": "MyZubster Gateway is running!",
"timestamp": "2026-07-24T..."
}
🔧 2. 환경 설정 (Environment Configuration)
2.1 프로덕션(.env) 파일
VPS에서 프로덕션을 위한 .env 파일을 생성하세요:
bash
nano .env
env
PORT=3001
MONGODB_URI=mongodb://localhost:27017/myzubster
JWT_SECRET=fd2cb60aba88af3ffc3832c8354cd1c8d4e0a9bb47dcd0f105ecaaa11dc23831801e214087c5745ec8ba675c43b05f387222714b047253a4cc405e43ac395f92
NODE_ENV=production
DeepSeek AI
DEEPSEEK_API_KEY=your_production_deepseek_api_key
DEEPSEEK_MODEL=deepseek-chat
DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions
Monero (프로덕션용 메인넷)
MONERO_RPC_URL=http://localhost:18082/json_rpc
MONERO_WALLET_ADDRESS=your_monero_wallet_address
MONERO_VIEW_KEY=your_monero_view_key
MONERO_NETWORK=mainnet
결제 모드 (Payment Mode)
PAYMENT_MODE=real
프런트엔드 (Frontend)
FRONTEND_URL=https://myzubster.com
2.2 안전한 JWT Secret 생성
bash
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
출력을 복사하여 JWT_SECRET으로 사용하세요.
2.3 .gitignore 설정
.env 및 기타 민감한 파일이 Git에서 제외되었는지 확인하세요:
gitignore
환경 변수 (Environment variables)
.env
.env.local
.env.*.local
.env.production
.env.development
노드 모듈 (Node modules)
node_modules/
로그 (Logs)
.log
pm-debug.log
OS 파일 (OS files)
.DS_Store
Thumbs.db
IDE
.vscode/
.idea/
임시 파일 (Temp files)
*.swp
*.save
📊 3. Database Models (데이터베이스 모델)
3.1 Existing Models (기존 모델)
| Model (모델) | File (파일) | Purpose (용도) |
|---|---|---|
| User (사용자) | models/User.js | 사용자 계정, 인증 (authentication) |
| Order (주문) | models/Order.js | 사용자 간의 서비스 주문 |
3.2 New Models Added (새로 추가된 모델)
| Model (모델) | File (파일) | Purpose (용도) |
|---|---|---|
| Skill (기술) | models/Skill.js | 사용자가 제공하는 기술/역량 |
| Offer (제안) | models/Offer.js | 가용성을 포함한 활성 서비스 제안 |
| Request (요청) | models/Request.js | 사용자의 서비스 요청 |
| Transaction (트랜잭션) | models/Transaction.js | 결제 및 크레딧 내역 |
| Review (리뷰) | models/Review.js | 사용자 리뷰 및 평점 |
3.3 Model Example: Skill.js (모델 예시: Skill.js)
const mongoose = require('mongoose');
const SkillSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
required: true,
trim: true,
maxlength: 100
},
description: {
type: String,
required: true,
maxlength: 2000
},
category: {
type: String,
required: true,
enum: [
'Manutenzione', 'Bellezza', 'Informatica',
'Giardinaggio', 'Pulizie', 'Insegnamento',
'Arte', 'Salute', 'Altro'
]
},
zone: {
type: String,
required: true
},
pricePerHour: {
type: Number,
default: 0
},
fixedPrice: {
type: Number,
default: 0
},
pricingType: {
type: String,
enum: ['hourly', 'fixed'],
default: 'hourly'
},
isActive: {
type: Boolean,
default: true
}
}, {
timestamps: true
});
SkillSchema.index({ user: 1 });
SkillSchema.index({ category: 1 });
SkillSchema.index({ zone: 1 });
SkillSchema.index({ title: 'text', description: 'text' });
module.exports = mongoose.model('Skill', SkillSchema);
🔌 4. API 라우트 (API Routes)
4.1 사용 가능한 모든 라우트 (All Available Routes)
라우트 파일 엔드포인트 (Route File Endpoints)
Auth: routes/auth.js /api/auth/register, /api/auth/login
Skills: routes/skills.js /api/skills (CRUD)
Offers: routes/offers.js /api/offers (CRUD)
Requests: routes/requests.js /api/requests (CRUD)
Orders: routes/orders.js /api/orders (CRUD)
Payments: routes/payments.js /api/payments/create, /api/payments/status/:id
Transactions: routes/transactions.js /api/transactions (CRUD)
Reviews: routes/reviews.js /api/reviews (CRUD)
AI: routes/ai.js /api/ai/matchmaking, /api/ai/chat, /api/ai/generate-description
4.2 예시 API 요청: 스킬 생성 (Example API Request: Create a Skill)
curl -X POST [http://localhost:3000/api/skills](http://localhost:3000/api/skills) \
-H "Content-Type: application/json" \
-d '{
"user": "USER_ID_HERE",
"title": "Professional Plumber",
"description": "Fixing pipes, faucets, and boilers",
"category": "Manutenzione",
"zone": "Rimini Centro",
"pricePerHour": 0.5
}'
4.3 예시 API 요청: AI 매칭 (Example API Request: AI Matchmaking)
curl -X POST [http://localhost:3000/api/ai/matchmaking](http://localhost:3000/api/ai/matchmaking) \
-H "Content-Type: application/json" \
-d '{
"request": "Looking for a plumber to fix my boiler, Rimini Centro area"
}'
🤖 5. AI 통합 (AI Integration) (DeepSeek)
5.1 서비스 (Services)
AI 기능은 services/aiService.js에 구현되어 있습니다:
const aiService = require('../services/aiService');
// 매칭 (Matchmaking)
const professionals = await aiService.findBestMatch(userRequest, professionalsList);
// 챗봇 (Chatbot)
const response = await aiService.chatAssistant(userMessage);
// 설명 생성 (Generate Description)
const description = await aiService.generateDescription(title, category, zone, price);
5.2 AI 기능 (AI Features)
매칭 (Matchmaking) 지능화: 사용자 요청을 분석하고 관련성에 따라 전문가를 순위화합니다.
챗봇 어시스턴트 (Chatbot Assistant): 자주 묻는 질문(FAQs)에 답변하고 탐색을 지원합니다.
...
5.3 DeepSeek API 키 받기 (Getting a DeepSeek API Key)
platform.deepseek.com으로 이동합니다.
계정을 생성하거나 로그인합니다.
...
💳 6. 결제 시스템 (Mock)
6.1 Mock 결제 서비스
`services/paymentService.js`에 위치한 Mock (모의) 서비스는 다음과 같은 기능을 수행합니다:
랜덤 결제 ID 생성
주소 및 QR 코드 시뮬레이션
...
6.2 실제 결제로 전환하기
실제 Monero 결제를 활성화하려면 `.env` 파일에 다음과 같이 설정하십시오:
env
PAYMENT_MODE=real
그 후, Monero RPC를 사용하여 `services/realPaymentService.js`를 구현하십시오.
6.3 결제 API 엔드포인트 (Endpoints)
javascript
POST /api/payments/create
Body: { orderId, amount, currency }
Response: { success: true, data: { id, address, qrCode, amount, status } }
GET /api/payments/status/:paymentId
Response: { success: true, data: { status, confirmedAt, ... } }
POST /api/payments/confirm/:paymentId
Response: { success: true, data: { status: 'confirmed', ... } }
☁️ 7. VPS에 배포하기
7.1 초기 VPS 설정
VPS에 접속합니다:
bash
ssh root@your_vps_ip
시스템을 업데이트합니다:
bash
apt update && apt upgrade -y
7.2 Node.js (v20+) 설치
bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
apt install -y nodejs
node -v # v20.x가 표시되어야 합니다
7.3 MongoDB 설치
bash
# MongoDB GPG 키 추가
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
# MongoDB 저장소(Repository) 추가
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# MongoDB 설치
apt update
apt install -y mongodb-org
# MongoDB 시작
systemctl start mongod
systemctl enable mongod
systemctl status mongod
7.4 Git 및 PM2 설치
bash
apt install -y git
npm install -g pm2
7.5 VPS에 저장소(Repository) 클론하기
bash
git clone https://github.com/DanielIoni-creator/MyZubsterGateway.git
cd MyZubsterGateway
7.6 Git 인증 구성
옵션 A: 개인 액세스 토큰 (Personal Access Token)을 사용한 HTTPS 방식
```bash
git remote set-url origin https://YOUR_USERNAME@github.com/DanielIoni-creator/MyZubsterGateway.git
옵션 B: SSH 사용
ssh-keygen -t ed25519 -C "your-email@example.com"
cat ~/.ssh/id_ed25519.pub
# 키를 복사하여 GitHub > Settings > SSH Keys에 추가하세요.
7.7 종속성 설치 및 .env 구성
npm install
nano .env
운영 환경(production)용 .env 내용을 붙여넣고 저장하세요.
7.8 PM2로 서버 시작
PORT=3001 node server.js # 먼저 수동으로 테스트하세요
# 정상 작동한다면, Ctrl+C를 누른 후 다음을 실행하세요:
pm2 start server.js --name myzubster-gateway -- --PORT=3001
pm2 save
pm2 status
7.9 PM2 시작 구성
pm2 startup
# PM2가 표시하는 명령어를 실행하세요 (예: sudo env PATH=...)
🔄 8. PM2 관리
8.1 기본 명령어
# 모든 프로세스 목록 표시
pm2 list
# 프로세스 시작
pm2 start server.js --name myzubster-gateway -- --PORT=3001
# 프로세스 중지
pm2 stop myzubster-gateway
# 프로세스 재시작
pm2 restart myzubster-gateway
# 프로세스 삭제
pm2 delete myzubster-gateway
# 현재 프로세스 목록 저장
pm2 save
# 로그 표시
pm2 logs myzubster-gateway
pm2 logs myzubster-gateway --lines 50
8.2 모니터링
# 실시간 모니터링
pm2 monit
# 프로세스 상태
pm2 status
🐛 9. 문제 해결 (Troubleshooting)
9.1 포트가 이미 사용 중임 (EADDRINUSE)
프로세스 찾기:
lsof -i :3000
ss -tulpn | grep 3000
ps aux | grep node
프로세스 종료:
kill -9 [PID]
# 또는 모든 Node 프로세스 종료
pkill -9 node
9.2 Git 인증 실패
해결 방법 1: 개인 액세스 토큰 (Personal Access Token) 사용
GitHub에서 토큰을 생성합니다 (Settings → Developer settings → Personal access tokens)
비밀번호를 입력하라는 메시지가 뜨면 생성한 토큰을 사용하세요.
해결 방법 2: 원격 URL (remote URL) 변경
git remote set-url origin [https://YOUR_USERNAME@github.com/DanielIoni-creator/MyZubsterGateway.git](https://YOUR_USERNAME@github.com/DanielIoni-creator/MyZubsterGateway.git)
9.3 MongoDB 연결 문제 (MongoDB Connection Issues)
MongoDB가 실행 중인지 확인합니다:
```bash
systemctl status mongodb
systemctl start mongodb
systemctl enable mongodb
.env 파일의 MongoDB URI를 확인합니다:
MONGODB_URI=mongodb://localhost:27017/myzubster
9.4 PM2 프로세스 찾을 수 없음 (PM2 Process Not Found)
# 프로세스 시작
pm2 start server.js --name myzubster-gateway -- --PORT=3001
pm2 save
# 또는 모두 종료 후 재시작
pm2 kill
pm2 start server.js --name myzubster-gateway -- --PORT=3001
pm2 save
9.5 중복 스키마 인덱스 경고 (Mongoose)
수정 방법: models/User.js에서 중복된 인덱스 정의를 제거합니다:
// 스키마 필드에서 unique: true 제거
username: { type: String, required: true, trim: true }
email: { type: String, required: true, trim: true, lowercase: true }
// 인덱스 정의만 유지
UserSchema.index({ email: 1 }, { unique: true });
UserSchema.index({ username: 1 }, { unique: true });
데이터베이스에서 오래된 인덱스를 정리합니다:
node cleanup.js
9.6 서버 응답 없음 (Server Not Responding)
서버가 실행 중인지 확인합니다:
pm2 status
lsof -i :3001
로그를 확인합니다:
pm2 logs myzubster-gateway
API를 테스트합니다:
curl [http://localhost:3001/api/health](http://localhost:3001/api/health)
🔗 10. 다음 단계 (Next Steps)
10.1 Nginx 설치 (리버스 프록시)
apt install -y nginx
AI 자동 생성 콘텐츠
본 콘텐츠는 Dev.to AI tag의 원문을 AI가 자동으로 요약·번역·분석한 것입니다. 원 저작권은 원저작자에게 있으며, 정확한 내용은 반드시 원문을 확인해 주세요.
원문 바로가기