aethex.live/docs/RAILWAY_COMPLETE_GUIDE.md

391 lines
7.7 KiB
Markdown

# Railway Deployment Guide for aethex.live
Since you're already using Railway, here's everything you need to deploy your streaming platform there.
## 📋 Table of Contents
1. [Quick Start](#quick-start)
2. [Full Setup](#full-setup)
3. [Adding Services](#adding-services)
4. [Environment Setup](#environment-setup)
5. [Monitoring & Debugging](#monitoring--debugging)
6. [Production Scaling](#production-scaling)
---
## Quick Start
The fastest way to get running:
### Step 1: Deploy the App
```bash
npm i -g @railway/cli
railway login
railway up
```
### Step 2: Add Stream URL
In Railway Dashboard → Variables:
```
NEXT_PUBLIC_STREAM_URL=your-hls-stream-url.m3u8
```
### Step 3: Add Domain
In Railway Dashboard → Domains → Add:
- Domain: `aethex.live`
- Add DNS CNAME record to your domain registrar
**Done!** Your app is live. 🎉
---
## Full Setup
### Project Structure on Railway
```
aethex.live
├── Web Service (Next.js app)
├── PostgreSQL (optional - for chat/data)
├── Redis (optional - for viewer count/cache)
└── Environment Variables
```
### Step 1: Connect GitHub
1. Go to https://railway.app/dashboard
2. Click "New Project"
3. Select "Deploy from GitHub"
4. Choose `aethex.live` repository
5. Connect and authorize
### Step 2: Configure Environment
Add these environment variables:
**Required:**
```
NEXT_PUBLIC_STREAM_URL=your-hls-stream-url.m3u8
NODE_ENV=production
```
**Optional (for features):**
```
# If using database
DATABASE_URL=<auto-set by Railway if you add PostgreSQL>
# If adding authentication
NEXTAUTH_URL=https://aethex.live
NEXTAUTH_SECRET=generate-random-secret-here
# If using WebSocket
NEXT_PUBLIC_WEBSOCKET_URL=wss://aethex.live/socket.io
```
### Step 3: Deploy
Railway auto-deploys on push to main:
```bash
git push origin main
```
Or manually trigger:
```bash
railway up
```
---
## Adding Services
### Add Database (PostgreSQL)
Perfect for storing chat, users, streams, etc.
1. Railway Dashboard → Click "+" → Add Database
2. Select **PostgreSQL**
3. Railway auto-sets `DATABASE_URL` environment variable
4. Use examples from `docs/RAILWAY_POSTGRES_EXAMPLE.tsx`
Then initialize your database:
```sql
-- Run this once to create the messages table
CREATE TABLE IF NOT EXISTS messages (
id SERIAL PRIMARY KEY,
username VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_timestamp ON messages(timestamp DESC);
```
### Add Redis (Caching & Real-Time)
Great for viewer count and caching:
1. Railway Dashboard → Click "+" → Add Service
2. Marketplace → Search "Upstash Redis"
3. Add to project
4. Railway sets `UPSTASH_REDIS_*` variables automatically
See `docs/VIEWER_COUNT_EXAMPLE.ts` for usage.
### Connect External Services
If using external services (Cloudflare, Stripe, etc.):
1. Get API keys from the service
2. Add as environment variables in Railway
3. Use in your code via `process.env.YOUR_API_KEY`
---
## Environment Setup
### Local Development
Copy Railway's env vars locally:
```bash
railway vars fetch >> .env.local
```
This pulls all environment variables from Railway into your local `.env.local`.
### Environment Variables Explained
| Variable | Purpose | Example |
|----------|---------|---------|
| `NEXT_PUBLIC_STREAM_URL` | HLS stream URL | `https://...m3u8` |
| `DATABASE_URL` | PostgreSQL connection | Set by Railway |
| `NEXTAUTH_SECRET` | Auth secret | `random-key-here` |
| `NODE_ENV` | Environment | `production` |
| `UPSTASH_REDIS_REST_URL` | Redis endpoint | Set by Railway |
**Important:** Variables starting with `NEXT_PUBLIC_` are exposed to the browser. Never put secrets there!
---
## Monitoring & Debugging
### View Logs
```bash
# Live logs
railway logs
# Or in dashboard: Deployments → View Logs
```
### Monitor Performance
Railway Dashboard → Deployments → Metrics:
- CPU usage
- Memory usage
- Network I/O
- Build time
### Troubleshoot Issues
| Problem | Solution |
|---------|----------|
| App crashes on startup | Check logs for errors, verify `npm start` works |
| Can't connect to database | Verify `DATABASE_URL` is set, check firewall |
| Stream won't load | Verify `NEXT_PUBLIC_STREAM_URL` is correct |
| High memory usage | Check for memory leaks, consider caching |
| Slow builds | Check dependencies, consider build optimization |
### Enable Debug Mode
Add to environment:
```
DEBUG=*
NODE_ENV=development
```
---
## Production Scaling
### Handle Growth
As your viewers increase:
#### 1. Upgrade Instance Size
```
Railway Dashboard → Settings → Instance Size
- Standard ($5-20/month): Great for streaming
- Pro: For high traffic
```
#### 2. Add Multiple Replicas
In Railway Dashboard → Settings → Deploy:
- Set `numReplicas: 2` or higher for load balancing
Or in `railway.json`:
```json
{
"deploy": {
"numReplicas": 3
}
}
```
#### 3. Add CDN (Cloudflare)
```
1. Add Cloudflare in front of Railway
2. Points: aethex.live → Cloudflare → Railway
3. Benefits: Caching, DDoS protection, global speed
```
#### 4. Database Optimization
```sql
-- Add indexes for common queries
CREATE INDEX idx_messages_username ON messages(username);
CREATE INDEX idx_messages_timestamp ON messages(timestamp DESC);
-- Monitor slow queries
EXPLAIN ANALYZE SELECT * FROM messages WHERE ...;
```
#### 5. Caching Strategy
Use Redis for:
- Session data
- View count
- Popular chat messages
- API responses
---
## Cost Management
Railway pricing:
- **Compute**: $0.07/month per CPU-hour
- **Memory**: $0.07/month per GB-hour
- **Databases**: $15-30/month depending on size
**Estimated monthly cost:**
- Small app: $5-10/month
- Medium app: $20-50/month
- Large app: $50+/month
**Save money:**
- Stop unused projects
- Use free tier ($5 credit/month)
- Use Railway's managed Redis instead of self-hosted
- Enable auto-scaling instead of always-on
---
## Deployment Checklist
Before going live:
- [ ] Stream URL configured
- [ ] Environment variables set
- [ ] Domain configured
- [ ] SSL certificate active (auto)
- [ ] Logs reviewed for errors
- [ ] Test stream verified
- [ ] Chat working (if enabled)
- [ ] Mobile responsive
- [ ] Analytics enabled
- [ ] Monitoring configured
- [ ] Backup plan documented
---
## Continuous Deployment
Railway auto-deploys on push:
```
You push → GitHub → Railway detects → Auto builds → Auto deploys → Live!
```
Disable auto-deploy if needed:
```
Dashboard → Settings → Disable Auto Deploy
```
Then manually deploy:
```bash
railway up
```
---
## Useful Commands
```bash
# Status
railway status
# View logs
railway logs -f # follow mode
# Open dashboard
railway open
# Set variable
railway variables set KEY=value
# Pull all vars
railway vars fetch
# Redeploy
railway up
# Stop project
railway stop
# View project info
railway whoami
railway projects list
```
---
## Next Steps
1. ✅ Deploy to Railway (this guide)
2. ✅ Configure your stream URL
3. **Next**: Add real-time features
- Chat with PostgreSQL (see `docs/RAILWAY_POSTGRES_EXAMPLE.tsx`)
- WebSocket support (see `docs/WEBSOCKET_EXAMPLE.ts`)
- Real-time viewer count (see `docs/VIEWER_COUNT_EXAMPLE.ts`)
4. Add user authentication
5. Set up analytics
6. Monetize (subscriptions, donations)
---
## Resources
- **Railway Docs**: https://docs.railway.app
- **Railway CLI**: https://docs.railway.app/reference/cli
- **Next.js on Railway**: https://docs.railway.app/guides/nextjs
- **Railway Community**: https://discord.gg/railway
---
## Support
Having issues?
1. Check logs: `railway logs`
2. Review this guide for your use case
3. Check Railway docs
4. Community Discord: https://discord.gg/railway
5. Railway support: https://railway.app/support
---
**Your streaming platform is now on Railway! 🚀 Start streaming!**