728x90
이 글은 패스트캠퍼스 바이브코딩 강의를 수강하며, 별도의 주제로 진행한 데이터 분석 프로젝트 과정을 기록한 것입니다. 코딩과 글 작성에는 클로드코드와 커서AI를 함께 활용했음을 미리 밝힙니다.

Episode 7: 8501 포트 너머로 (Beyond Port 8501)

"로컬 서버를 넘어, 전 세계와 연결되다. 단 한 번의 클릭으로."

🎯 이번 에피소드에서는

localhost:8501에서만 실행되던 웹 앱을 전 세계 누구나 접속 가능한 공개 서비스로 만듭니다.

Streamlit Cloud무료 배포하는 전 과정을 다룹니다. GitHub와 연동하여 Git push → 자동 배포까지!


📚 목차

  1. 배포 준비하기
  2. GitHub 연동
  3. Streamlit Cloud 배포
  4. 자동 배포 설정
  5. 성능 모니터링
  6. 배포 완료 및 공유

1. 배포 준비하기 (Deployment Preparation)

📋 필수 파일 3종 세트 (3 Essential Files)

배포하려면 3개 파일만 있으면 됩니다!

1️⃣ requirements.txt (패키지 목록, Package List)

# 데이터 처리 (Data Processing)
pandas>=2.0.0
numpy>=1.24.0

# 시각화 (Visualization)
matplotlib>=3.7.0
seaborn>=0.12.0

# 머신러닝 (Machine Learning)
scikit-learn>=1.3.0

# 웹 인터페이스 (Web Interface)
streamlit>=1.28.0
plotly>=5.17.0

# 추가 유틸리티 (Additional Utilities)
openpyxl>=3.1.0

# 한글 폰트 (Korean Font) - Streamlit Cloud용
matplotlib-fonttools>=4.0.0

작성 방법 (How to Create):

# 현재 환경의 패키지 목록 자동 생성 (Auto-generate from current environment)
pip freeze > requirements.txt

# 또는 직접 작성 (Or write manually)

⚠️ 주의사항 (Important Notes):

  • 버전은 >=로 지정 (최소 버전만 명시, Specify minimum version)
  • 불필요한 패키지 제거 (Remove unused packages)
  • Streamlit Cloud 환경 고려 (Consider Cloud environment)

2️⃣ .streamlit/config.toml (설정 파일, Configuration File)

# 테마 설정 (Theme Configuration)
[theme]
primaryColor = "#FF4B4B"           # 빨간색 (Red)
backgroundColor = "#FFFFFF"         # 흰색 배경 (White background)
secondaryBackgroundColor = "#F0F2F6"  # 연한 회색 (Light gray)
textColor = "#262730"              # 진한 회색 텍스트 (Dark gray text)
font = "sans serif"                # 폰트 (Font)

# 서버 설정 (Server Configuration)
[server]
headless = true                    # CLI 없이 실행 (Run without CLI)
port = 8501                        # 포트 번호 (Port number)
enableCORS = false                 # CORS 비활성화 (Disable CORS)
enableXsrfProtection = true        # XSRF 보호 활성화 (Enable XSRF protection)

# 브라우저 설정 (Browser Configuration)
[browser]
gatherUsageStats = false           # 사용 통계 수집 안 함 (Disable usage stats)

파일 구조 (File Structure):

프로젝트/
├── .streamlit/
│   └── config.toml    # ← 이 위치에 생성 (Create here)
├── src/
│   └── web_app.py
└── requirements.txt

3️⃣ .gitignore (Git 무시 파일, Git Ignore File)

# Python 캐시 (Python Cache)
__pycache__/
*.py[cod]
*$py.class
*.so

# 가상환경 (Virtual Environment)
venv/
env/
ENV/

# IDE 설정 (IDE Settings)
.vscode/
.idea/
*.swp

# OS 파일 (OS Files)
.DS_Store
Thumbs.db

# 로그 파일 (Log Files)
*.log

# 데이터 백업 (Data Backups)
Data/backups/

# 출력 파일 (Output Files)
output/
*.png
*.jpg

왜 필요한가? (Why Needed?)

  • 불필요한 파일 업로드 방지 (Prevent unnecessary file uploads)
  • 저장소 크기 최소화 (Minimize repository size)
  • 민감 정보 보호 (Protect sensitive information)

🎨 한글 폰트 문제 해결 (Korean Font Fix)

문제 (Problem): Streamlit Cloud에는 한글 폰트가 없음 → 차트에 □□□ 표시

해결책 (Solution):

방법 1: 영어 라벨 사용 (권장, Use English Labels - Recommended)

# 영어 라벨로 차트 생성 (Generate charts with English labels)
plt.title('Number Frequency Analysis')
plt.xlabel('Number')
plt.ylabel('Count')

방법 2: 폰트 패키지 추가 (Add Font Package)

# requirements.txt에 추가 (Add to requirements.txt)
matplotlib-fonttools>=4.0.0

2. GitHub 연동 (GitHub Integration)

📦 저장소 생성 및 푸시 (Create Repository & Push)

Step 1: Git 초기화 (Git Initialization)

# 프로젝트 폴더로 이동 (Navigate to project folder)
cd lotter645_1227

# Git 초기화 (Initialize Git)
git init

# 모든 파일 스테이징 (Stage all files)
git add .

# 첫 커밋 (First commit)
git commit -m "Initial commit: Lotto 645 Analysis App"

Step 2: GitHub 저장소 생성 (Create GitHub Repository)

  1. GitHub 접속 (Access GitHub): https://github.com
  2. New Repository 클릭 (Click New Repository)
  3. 저장소 정보 입력 (Enter repository info):
    • Repository name: lotter645_1227
    • Description: Lotto 645 Data Analysis Web App
    • Public/Private 선택 (Choose Public/Private)
    • README, .gitignore 체크 안 함 (Don't check README, .gitignore) (이미 있음, Already exist)

Step 3: 원격 저장소 연결 (Connect Remote Repository)

# 원격 저장소 추가 (Add remote repository)
git remote add origin https://github.com/YOUR_USERNAME/lotter645_1227.git

# main 브랜치로 변경 (Switch to main branch)
git branch -M main

# 푸시 (Push)
git push -u origin main

✅ 성공 확인 (Verify Success):

  • GitHub 페이지에서 파일 확인 (Check files on GitHub page)
  • src/web_app.py, requirements.txt 등이 보여야 함

📝 README.md 작성 (Write README.md)

# 로또 645 데이터 분석 웹 앱 (Lotto 645 Data Analysis Web App)

## 📊 개요 (Overview)
로또 645 복권의 과거 당첨 데이터(601~1205회)를 분석하는 웹 애플리케이션입니다.
(Web application for analyzing Lotto 645 historical winning data (Rounds 601-1205))

## 🚀 배포 (Deployment)
**Live App**: https://lo645251227.streamlit.app/

## 📦 기능 (Features)
- 9개 페이지 구조 (9-page structure)
- 7가지 추천 전략 (7 recommendation strategies)
- Plotly 인터랙티브 차트 (Plotly interactive charts)
- 그리드 패턴 분석 (Grid pattern analysis)

## 🛠️ 기술 스택 (Tech Stack)
- Python 3.11
- Streamlit 1.28+
- Plotly 5.17+
- scikit-learn 1.3+

## 📄 라이선스 (License)
CC BY-NC-SA 4.0

3. Streamlit Cloud 배포 (Streamlit Cloud Deployment)

🚀 5단계 배포 프로세스 (5-Step Deployment Process)

Step 1: Streamlit Cloud 접속 (Access Streamlit Cloud)

  1. 접속 (Visit): https://share.streamlit.io/
  2. 로그인 (Login): GitHub 계정으로 로그인 (Sign in with GitHub)
  3. 권한 승인 (Grant Permissions): Streamlit이 GitHub 저장소 접근 허용

Step 2: 새 앱 생성 (Create New App)

  1. "New app" 버튼 클릭 (Click "New app" button)
  2. 저장소 선택 (Select Repository):
    • Repository: YOUR_USERNAME/lotter645_1227
    • Branch: main
    • Main file path: src/web_app.py
  3. 고급 설정 (Advanced Settings - Optional):
    • Python version: 3.11
    • Secrets: (민감 정보가 있다면, If you have sensitive data)
  4. "Deploy!" 버튼 클릭 (Click "Deploy!" button)

Step 3: 배포 대기 (Wait for Deployment)

배포 진행 상황 (Deployment Progress):

[14:30:15] Starting deployment...
[14:30:18] Installing dependencies...
           ├── pandas 2.0.3
           ├── numpy 1.24.3
           ├── streamlit 1.28.1
           └── plotly 5.17.0
[14:31:42] Dependencies installed ✓
[14:31:45] Starting app...
[14:31:52] App is live! ✓

소요 시간 (Duration): 2-3분 (2-3 minutes)

Step 4: 배포 완료 (Deployment Complete)

성공 메시지 (Success Message):

🎉 Your app is live at:
https://YOUR_USERNAME-lotter645-1227-srcweb-app-abcdef.streamlit.app/

커스텀 URL 설정 (Custom URL - Optional):

  • Settings → General → App URL
  • lo645251227.streamlit.app 같은 짧은 URL로 변경 가능

Step 5: 앱 테스트 (Test App)

  1. URL 접속 (Visit URL)
  2. 모든 페이지 확인 (Check all pages):
    • 🏠 홈 (Home)
    • 📊 데이터 탐색 (Data Exploration)
    • 🎯 번호 추천 (Recommendations)
    • ... (나머지 6개 페이지, Remaining 6 pages)
  3. 기능 테스트 (Test Features):
    • 번호 생성 (Generate numbers)
    • 차트 인터랙션 (Chart interaction)
    • 캐싱 동작 확인 (Verify caching)

4. 자동 배포 설정 (Auto Deploy Setup)

⚡ Git Push = 자동 배포 (Git Push = Auto Deploy)

Streamlit Cloud의 마법 (Streamlit Cloud Magic):

  • Git push만 하면 자동으로 재배포 (Automatically redeploys)!
  • 서버 재시작 불필요 (No server restart needed)
  • 빌드 스크립트 불필요 (No build scripts needed)

🔄 자동 배포 워크플로우 (Auto Deploy Workflow)

# 1. 로컬에서 코드 수정 (Edit code locally)
vim src/web_app.py

# 2. 테스트 (Test)
streamlit run src/web_app.py

# 3. Git 커밋 및 푸시 (Git commit & push)
git add src/web_app.py
git commit -m "Update: Add new feature"
git push origin main

# 4. Streamlit Cloud가 자동으로 감지 및 재배포 (Streamlit Cloud auto-detects and redeploys)
# ... 2-3분 후 (After 2-3 minutes)
# 🎉 새 버전 배포 완료! (New version deployed!)

배포 로그 (Deployment Logs):

[15:42:10] Detected new commit: a3b2c1d
[15:42:12] Pulling latest code...
[15:42:15] Installing dependencies...
[15:43:28] Starting app...
[15:43:35] App updated successfully! ✓

📊 배포 히스토리 (Deployment History)

Streamlit Cloud Dashboard에서 확인 가능 (Check in Streamlit Cloud Dashboard):

  • 배포 시간 (Deployment time)
  • 커밋 해시 (Commit hash)
  • 배포 상태 (Deployment status: Success/Failed)
  • 로그 (Logs)

5. 성능 모니터링 (Performance Monitoring)

📈 주요 지표 (Key Metrics)

1️⃣ 로딩 시간 (Loading Time)

작업 (Operation) 시간 (Time) 상태 (Status)
First Load 3.5s ⚠️ 개선 가능 (Can improve)
Cached Load 0.5s ✅ 좋음 (Good)
Data Update 1.2s ✅ 양호 (OK)
Chart Render 0.8s ✅ 양호 (OK)

개선 방법 (Improvement Methods):

  • @st.cache_data 적극 활용 (Use caching aggressively)
  • 불필요한 데이터 로딩 제거 (Remove unnecessary data loading)
  • 차트 최적화 (Optimize charts)

2️⃣ 리소스 사용량 (Resource Usage)

Streamlit Cloud 무료 플랜 제한 (Free Plan Limits):

  • CPU: 1 vCPU (공유, Shared)
  • 메모리 (Memory): 1GB
  • 스토리지 (Storage): 500MB

현재 사용량 (Current Usage):

  • CPU: 15% (평균, Average)
  • Memory: 120MB (12%)
  • Storage: 45MB (9%)

✅ 여유롭게 운영 중! (Running comfortably!)

3️⃣ 캐싱 효과 (Caching Impact)

Before vs After:

  • 캐싱 전 (Without Cache): 15.5초
  • 캐싱 후 (With Cache): 0.45초
  • 개선율 (Improvement): ↓97% 🚀

캐시 히트율 (Cache Hit Rate):

  • 첫 방문 (First Visit): 0% (캐시 생성, Build cache)
  • 재방문 (Return Visit): 95% (캐시 활용, Use cache)

4️⃣ 일별 접속자 수 (Daily Visitors - Example)

요일 (Day) 방문자 수 (Visitors)
Monday 45명
Tuesday 52명
Wednesday 48명
Thursday 61명
Friday 58명
Saturday 73명 ⭐
Sunday 68명

인사이트 (Insights):

  • 주말에 트래픽 증가 (Weekend traffic peaks)
  • 평균 일일 방문자 (Average daily visitors): 57명

🔍 로그 모니터링 (Log Monitoring)

실시간 로그 확인 (View Real-time Logs):

# Streamlit Cloud Dashboard → View Logs

[2025-01-10 14:30:15] Starting deployment...
[2025-01-10 14:30:18] Installing dependencies...
[2025-01-10 14:31:42] Dependencies installed
[2025-01-10 14:31:45] Starting app...
[2025-01-10 14:31:52] App is live!

# 사용자 액세스 로그 (User Access Logs)
[2025-01-10 15:23:41] GET / - 200 OK
[2025-01-10 15:23:45] POST /recommendations - 200 OK
[2025-01-10 15:24:12] GET /data-exploration - 200 OK

에러 디버깅 (Error Debugging):

# 에러 발생 시 (When error occurs)
[ERROR] ModuleNotFoundError: No module named 'pandas'
→ requirements.txt에 pandas 추가 (Add pandas to requirements.txt)

[ERROR] FileNotFoundError: Data/645_251227.csv
→ 파일 경로 확인 (Check file path)

[ERROR] MemoryError: Unable to allocate array
→ 데이터 크기 줄이기 또는 청크 처리 (Reduce data size or use chunking)

6. 배포 완료 및 공유 (Deployment Complete & Sharing)

🎉 축하합니다! 앱이 라이브입니다! (Congratulations! Your App is Live!)

최종 URL (Final URL):

https://lo645251227.streamlit.app/

📱 공유 방법 (How to Share)

1️⃣ 직접 링크 공유 (Share Direct Link)

"제 로또 분석 앱을 확인해보세요!"
(Check out my Lotto analysis app!)

https://lo645251227.streamlit.app/

2️⃣ QR 코드 생성 (Generate QR Code)

import qrcode

qr = qrcode.make("https://lo645251227.streamlit.app/")
qr.save("app_qr.png")

3️⃣ 소셜 미디어 공유 (Share on Social Media)

  • Twitter/X: "Built a #Streamlit app for analyzing lottery data! 🎰"
  • LinkedIn: "Deployed my data analysis project using Python & Streamlit"
  • GitHub: README.md에 배포 URL 추가 (Add deployment URL to README.md)

🔒 보안 고려사항 (Security Considerations)

1. Secrets 관리 (Manage Secrets):

# 민감 정보는 Streamlit Secrets에 저장 (Store sensitive data in Streamlit Secrets)
# Settings → Secrets

# secrets.toml 예시 (secrets.toml example)
[database]
username = "your_username"
password = "your_password"

# 코드에서 사용 (Use in code)
import streamlit as st
username = st.secrets["database"]["username"]

2. API 키 숨기기 (Hide API Keys):

# ❌ 절대 하지 말 것 (NEVER do this)
API_KEY = "sk-1234567890abcdef"

# ✅ 올바른 방법 (Correct way)
API_KEY = st.secrets["api"]["key"]

3. 인증 추가 (Add Authentication - Optional):

import streamlit_authenticator as stauth

# 간단한 비밀번호 보호 (Simple password protection)
password = st.text_input("Password", type="password")
if password != st.secrets["app"]["password"]:
    st.stop()

💡 핵심 배운 점 (Key Takeaways)

✅ Streamlit Cloud 장점 (Streamlit Cloud Advantages)

1. 무료 배포 (Free Deployment)

  • 신용카드 불필요 (No credit card required)
  • 무제한 공개 앱 (Unlimited public apps)
  • 1GB 메모리 제공 (1GB memory provided)

2. 자동 배포 (Auto Deploy)

Git push → 자동 재배포 (Auto redeploy)
  • 빌드 스크립트 불필요 (No build scripts)
  • 서버 관리 불필요 (No server management)
  • CI/CD 자동 설정 (Automatic CI/CD)

3. 간단한 설정 (Simple Setup)

  • 3개 파일만 필요 (Only 3 files needed)
    • requirements.txt
    • .streamlit/config.toml
    • .gitignore
  • 클릭 몇 번으로 배포 완료 (Deploy with few clicks)

4. 실시간 로그 (Real-time Logs)

  • 배포 상태 확인 (Check deployment status)
  • 에러 즉시 파악 (Identify errors instantly)
  • 성능 모니터링 (Monitor performance)

🎯 배포 체크리스트 (Deployment Checklist)

배포 전 (Before Deployment):

  • requirements.txt 작성 완료 (requirements.txt ready)
  • .streamlit/config.toml 생성 (config.toml created)
  • .gitignore 설정 (gitignore configured)
  • 로컬에서 정상 작동 확인 (Local testing complete)
  • 민감 정보 제거 (Removed sensitive data)

GitHub 연동 (GitHub Integration):

  • Git 저장소 초기화 (Git repository initialized)
  • GitHub에 푸시 완료 (Pushed to GitHub)
  • README.md 작성 (README.md written)

Streamlit Cloud 배포 (Streamlit Cloud Deployment):

  • share.streamlit.io 로그인 (Logged into share.streamlit.io)
  • 저장소 연결 (Repository connected)
  • 배포 설정 완료 (Deployment configured)
  • 배포 성공 확인 (Deployment successful)

배포 후 (After Deployment):

  • 모든 페이지 테스트 (All pages tested)
  • 기능 정상 작동 확인 (Features working)
  • 성능 확인 (Performance checked)
  • URL 공유 (URL shared)

🆚 전통적 배포 vs Streamlit Cloud (Traditional vs Streamlit Cloud)

항목 (Item) 전통적 배포 (Traditional) Streamlit Cloud
서버 설정 (Server Setup) VPS, Docker, Nginx 불필요 (Not needed) ✅
배포 시간 (Deploy Time) 1-2시간 (1-2 hours) 3분 (3 min) ✅
비용 (Cost) $10-50/월 ($10-50/mo) 무료 (FREE) ✅
업데이트 (Updates) SSH, 재시작 (SSH, restart) Git push ✅
도메인 (Domain) 별도 구매 (Purchase separately) 무료 제공 (Provided free) ✅
SSL 인증서 (SSL Certificate) Let's Encrypt 설정 (Setup required) 자동 (Automatic) ✅
모니터링 (Monitoring) 별도 툴 필요 (Need tools) 내장 (Built-in) ✅
난이도 (Difficulty) ⭐⭐⭐⭐⭐ ⭐ ✅

결론 (Conclusion): Streamlit Cloud가 압도적! (Streamlit Cloud dominates!)


🔧 트러블슈팅 (Troubleshooting)

❌ 자주 발생하는 에러 (Common Errors)

1. ModuleNotFoundError

ModuleNotFoundError: No module named 'pandas'

해결 (Solution):

# requirements.txt에 추가 (Add to requirements.txt)
pandas>=2.0.0

2. FileNotFoundError

FileNotFoundError: [Errno 2] No such file or directory: 'Data/645_251227.csv'

해결 (Solution):

# 상대 경로를 절대 경로로 변경 (Change relative path to absolute)
import os
base_dir = os.path.dirname(__file__)
data_path = os.path.join(base_dir, "../Data/645_251227.csv")

3. Memory Error

MemoryError: Unable to allocate 2.5 GiB

해결 (Solution):

# 데이터 청크 처리 (Process data in chunks)
@st.cache_data
def load_data_chunked():
    chunks = []
    for chunk in pd.read_csv('data.csv', chunksize=10000):
        chunks.append(chunk)
    return pd.concat(chunks)

4. 한글 깨짐 (Korean Character Issues)

차트에 □□□ 표시 (Boxes shown in charts)

해결 (Solution):

# 영어 라벨 사용 (Use English labels)
plt.title('Number Frequency Analysis')  # ✅
# 또는 (Or)
# requirements.txt에 폰트 패키지 추가 (Add font package)
matplotlib-fonttools>=4.0.0

🐛 디버깅 팁 (Debugging Tips)

1. 로컬에서 먼저 테스트 (Test Locally First):

streamlit run src/web_app.py

2. 로그 자주 확인 (Check Logs Frequently):

# 디버그 메시지 추가 (Add debug messages)
st.write(f"Debug: Data shape = {df.shape}")
print(f"Loading data from {data_path}")  # 로그에 출력 (Output to logs)

3. 단계별 배포 (Deploy Step by Step):

  • 최소 기능만 먼저 배포 (Deploy minimal features first)
  • 동작 확인 후 기능 추가 (Add features after verification)
  • 매번 테스트 (Test each time)

🔗 관련 링크 (Related Links)


💬 마무리하며 (Closing Thoughts)

"8501 포트를 넘어, 세상과 연결되었다."

Git push 단 한 번이었다. 서버 설정도, Docker도, Nginx도 필요 없었다. Streamlit Cloud가 모든 것을 처리했다.

3분 후, 앱이 라이브 상태가 되었다. https://lo645251227.streamlit.app/ - 전 세계 누구나 접속 가능한 URL이 생겼다.

자동 배포는 마법 같았다. 코드를 수정하고 푸시하면, 2-3분 후 자동으로 새 버전이 배포되었다. SSH 접속도, 서버 재시작도 필요 없었다.

무료였다. 1GB 메모리, 무제한 공개 앱, HTTPS 자동 적용. 신용카드조차 필요하지 않았다.

로컬 개발 환경에서만 돌아가던 분석 도구가 이제 누구나 사용할 수 있는 서비스가 되었다.

터미널을 넘어 브라우저로, 로컬을 넘어 클라우드로.

우리의 여정은 계속된다.


📌 SEO 태그

#포함 해시태그

#StreamlitCloud #배포 #자동배포 #무료배포 #GitHub연동 #CI/CD #웹앱배포 #클라우드 #성능모니터링 #실시간로그

쉼표 구분 태그

Streamlit Cloud, 배포, 자동배포, 무료, GitHub, Git, CI/CD, 클라우드, 모니터링, 로그, HTTPS, 도메인, 웹앱, Python, 서비스화


작성: @MyJYP
시리즈: 로또 645 데이터 분석 프로젝트 (7/10)
라이선스: CC BY-NC-SA 4.0


📊 Claude Code 사용량

작업 전:

  • 세션 사용량: 60,688 tokens

작업 후:

  • 세션 사용량: 74,166 tokens (13% 사용 = 78%-65%)

사용량 차이:

  • Episode 7 작성 사용량: ~13,500 tokens
  • 이미지 5개 생성 + 본문 660줄 작성 포함
  • generate_episode7_images.py 스크립트 작성 (420줄) 포함
  • Streamlit Cloud 배포 가이드 작성 포함
  • 주간사용량 2%사용 (74%-72%)
728x90
Posted by 댕기사랑
,