Railway Deployment Guide
Deploy backend-api to Railway with CI/CD
Railway Deployment Guide
This guide walks you through deploying the backend-api to Railway, a modern platform-as-a-service that offers simple deployment and automatic scaling.
Overview
Railway provides:
- Simple deployment from GitHub
- Automatic HTTPS/SSL certificates
- Environment variable management
- Built-in monitoring and logs
- Auto-scaling capabilities
- Zero-downtime deployments
Prerequisites
- Railway account (free tier available)
- GitHub repository access
- Environment variables ready
- Railway CLI installed (optional)
Railway Project Setup
Project Information
- Project ID:
3990549d-4313-47e4-9682-d17b382bdba2 - Project Type: Backend API
- Runtime: Node.js 24
- Port: 3000 (automatically assigned by Railway)
1. Access Railway Dashboard
Visit: https://railway.app/project/3990549d-4313-47e4-9682-d17b382bdba2
2. Environment Variables Configuration
In the Railway dashboard, configure the following environment variables:
Required Variables
MONGODB_CONNECTION_STRING=mongodb+srv://username:[email protected]/
MONGODB_DATABASE=gograb-api
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
GOOGLE_API_KEY=your-google-key
JWT_SECRET=your-production-jwt-secret
JWT_EXPIRATION=7d
NODE_ENV=production
PORT=${{PORT}}
CORS Configuration
After deploying your frontend, update:
ALLOWED_ORIGINS=https://your-frontend-domain.com,https://your-admin-domain.com
Important Security Notes:
- Generate a NEW JWT secret for production (don't reuse development secret)
- Use different API keys for production than development
- Keep all secrets secure and never commit them to version control
Deployment Methods
Method 1: Railway CLI (Recommended for First Deployment)
Install Railway CLI
npm install -g @railway/cli
Link Project
# Navigate to your project root
cd /path/to/your/project
# Login to Railway
railway login
# Link to existing project
railway link 3990549d-4313-47e4-9682-d17b382bdba2
Deploy
railway up
Method 2: GitHub Integration (Recommended for CI/CD)
Setup
- Go to Railway dashboard
- Navigate to your project
- Click "Settings" → "GitHub"
- Connect your GitHub repository
- Select the branch to deploy (e.g.,
mainorferrari-2)
Configure Build Settings
Railway will automatically detect the Dockerfile. Verify:
- Root Directory:
/ - Dockerfile Path:
deployment/Dockerfile.railway.backend - Build Command: (automatic via Dockerfile)
- Start Command:
node dist/apis/backend-api/main.js
Enable Auto-Deploy
- In project settings, enable "Auto-Deploy"
- Select branch for deployment
- Railway will automatically deploy on every push to that branch
Method 3: Using Package.json Scripts
# Deploy backend using yarn script
yarn railway:deploy:backend
# Or using the deployment script directly
./deployment/railway-multi-project.sh deploy backend
Configuration Files
Railway Configuration (railway.backend.toml)
# Railway Backend Project Configuration
# Project ID: 3990549d-4313-47e4-9682-d17b382bdba2
[build]
builder = "dockerfile"
dockerfilePath = "deployment/Dockerfile.railway.backend"
[deploy]
startCommand = "node dist/apis/backend-api/main.js"
healthcheckPath = "/api/health"
healthcheckTimeout = 300
restartPolicyType = "ON_FAILURE"
restartPolicyMaxRetries = 10
[environments.production]
NODE_ENV = "production"
PORT = "${PORT}"
Dockerfile (deployment/Dockerfile.railway.backend)
The Dockerfile is optimized for Railway with:
- Node 24-alpine base image
- Multi-stage build for smaller image size
- Dependency caching
- Health check configuration
- Production-ready optimizations
Post-Deployment Steps
1. Verify Deployment
After deployment completes:
# Get your Railway deployment URL from the dashboard
# Example: https://backend-api-production-xxxx.up.railway.app
# Test health endpoint
curl https://your-railway-url.up.railway.app/api/health
Expected response:
{
"status": "ok",
"timestamp": "2025-01-15T12:00:00.000Z",
"service": "backend-api",
"version": "1.0.0"
}
2. Update Frontend Configuration
Update your frontend environment files with the Railway URL:
gograb-space:
// apps/gograb-space/src/environments/environment.prod.ts
export const environment = {
production: true,
backendApiUrl: 'https://your-railway-url.up.railway.app/api',
apiTimeout: 30000,
enableDebugMode: false
};
space-admin:
// apps/space-admin/src/environments/environment.prod.ts
export const environment = {
production: true,
backendApiUrl: 'https://your-railway-url.up.railway.app/api',
apiTimeout: 30000,
enableDebugMode: false
};
3. Update CORS Configuration
In Railway dashboard, update the ALLOWED_ORIGINS variable to include your deployed frontend URLs:
ALLOWED_ORIGINS=https://your-frontend.com,https://your-admin.com
4. Test All Endpoints
# Set your Railway URL
export API_URL="https://your-railway-url.up.railway.app/api"
# Test health
curl $API_URL/health
# Test root endpoint
curl $API_URL
# Test auth registration
curl -X POST $API_URL/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"Test123!","name":"Test"}'
# Test login
curl -X POST $API_URL/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"Test123!"}'
Monitoring and Logs
View Logs
Via Dashboard:
- Go to Railway project dashboard
- Click on your service
- Navigate to "Logs" tab
- View real-time logs
Via CLI:
railway logs
Monitor Resources
Railway dashboard provides:
- CPU usage
- Memory usage
- Network traffic
- Request counts
- Error rates
Health Checks
Railway automatically monitors the health endpoint at /api/health:
- Check interval: 30 seconds
- Timeout: 300 seconds
- Restarts service if health check fails
Troubleshooting
Build Failures
Issue: Build fails during deployment
Solutions:
- Check Railway build logs for specific error
- Verify Dockerfile path is correct in configuration
- Ensure all dependencies are in package.json
- Check Node.js version compatibility
# View detailed build logs
railway logs --build
Service Not Starting
Issue: Service deploys but doesn't start
Solutions:
- Verify start command is correct
- Check that PORT environment variable is properly set
- Review startup logs for errors
- Ensure MongoDB connection string is correct
Health Check Failures
Issue: Health check endpoint failing
Solutions:
- Verify health endpoint responds at
/api/health - Check MongoDB connectivity from Railway
- Ensure PORT is using Railway's assigned port
- Review application logs for startup errors
MongoDB Connection Issues
Issue: Cannot connect to MongoDB from Railway
Solutions:
- Verify MongoDB Atlas IP whitelist includes Railway IPs (use 0.0.0.0/0)
- Check connection string URL encoding
- Verify MongoDB database user permissions
- Test connection string locally first
CORS Errors in Production
Issue: Frontend cannot access backend due to CORS
Solutions:
- Verify ALLOWED_ORIGINS includes your frontend domain
- Ensure no trailing slashes in origin URLs
- Check CORS headers in response:
curl -I https://your-railway-url.up.railway.app/api/health \ -H "Origin: https://your-frontend.com" - Restart service after updating CORS configuration
Environment Variables Not Loading
Issue: Environment variables not available to application
Solutions:
- Verify variables are set in Railway dashboard
- Check variable names match exactly (case-sensitive)
- Restart service after adding variables
- Use Railway CLI to verify:
railway variables
Cost Optimization
Free Tier Limits
Railway free tier includes:
- $5 credit per month
- 500 hours of execution time
- Automatic scaling
Cost Monitoring
Monitor usage in Railway dashboard:
- View "Usage" tab
- Check monthly spending
- Set up spending alerts
Optimization Tips
- Use Hobby Plan: For production, upgrade to Hobby plan ($5/month)
- Optimize Build: Use efficient Dockerfile to reduce build times
- Scale Appropriately: Start with minimal resources, scale as needed
- Monitor Memory: Check memory usage and adjust if needed
CI/CD Best Practices
Automated Testing
Before deployment, run tests:
# .github/workflows/deploy-backend.yml
name: Deploy Backend to Railway
on:
push:
branches: [main]
paths:
- 'apis/backend-api/**'
- 'libs/api-contracts/**'
- 'libs/backend-core/**'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run tests
run: |
yarn install
yarn nx test backend-api
- name: Deploy to Railway
run: |
npm install -g @railway/cli
railway up
Deployment Notifications
Set up notifications for:
- Successful deployments
- Failed deployments
- Health check failures
Rollback Strategy
If deployment fails:
- Railway automatically keeps previous deployment running
- Use Railway dashboard to rollback to previous deployment
- Fix issues and redeploy
Security Checklist
Before deploying to production:
- New JWT secret generated for production
- All API keys are production keys (not development)
- MongoDB connection string uses production database
- ALLOWED_ORIGINS configured with production domains
- Environment variables reviewed and secured
- Health check endpoint tested
- HTTPS enabled (automatic with Railway)
- Database IP whitelist configured
- Monitoring and alerts set up
Next Steps
- API Reference - Complete endpoint documentation
- Local Development - Development setup
- Deployment Recommendation - Platform comparison