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:

Prerequisites

Railway Project Setup

Project Information

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:

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

  1. Go to Railway dashboard
  2. Navigate to your project
  3. Click "Settings" → "GitHub"
  4. Connect your GitHub repository
  5. Select the branch to deploy (e.g., main or ferrari-2)

Configure Build Settings

Railway will automatically detect the Dockerfile. Verify:

Enable Auto-Deploy

  1. In project settings, enable "Auto-Deploy"
  2. Select branch for deployment
  3. 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:

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:

  1. Go to Railway project dashboard
  2. Click on your service
  3. Navigate to "Logs" tab
  4. View real-time logs

Via CLI:

railway logs

Monitor Resources

Railway dashboard provides:

Health Checks

Railway automatically monitors the health endpoint at /api/health:

Troubleshooting

Build Failures

Issue: Build fails during deployment

Solutions:

  1. Check Railway build logs for specific error
  2. Verify Dockerfile path is correct in configuration
  3. Ensure all dependencies are in package.json
  4. Check Node.js version compatibility
# View detailed build logs
railway logs --build

Service Not Starting

Issue: Service deploys but doesn't start

Solutions:

  1. Verify start command is correct
  2. Check that PORT environment variable is properly set
  3. Review startup logs for errors
  4. Ensure MongoDB connection string is correct

Health Check Failures

Issue: Health check endpoint failing

Solutions:

  1. Verify health endpoint responds at /api/health
  2. Check MongoDB connectivity from Railway
  3. Ensure PORT is using Railway's assigned port
  4. Review application logs for startup errors

MongoDB Connection Issues

Issue: Cannot connect to MongoDB from Railway

Solutions:

  1. Verify MongoDB Atlas IP whitelist includes Railway IPs (use 0.0.0.0/0)
  2. Check connection string URL encoding
  3. Verify MongoDB database user permissions
  4. Test connection string locally first

CORS Errors in Production

Issue: Frontend cannot access backend due to CORS

Solutions:

  1. Verify ALLOWED_ORIGINS includes your frontend domain
  2. Ensure no trailing slashes in origin URLs
  3. Check CORS headers in response:
    curl -I https://your-railway-url.up.railway.app/api/health \
      -H "Origin: https://your-frontend.com"
    
  4. Restart service after updating CORS configuration

Environment Variables Not Loading

Issue: Environment variables not available to application

Solutions:

  1. Verify variables are set in Railway dashboard
  2. Check variable names match exactly (case-sensitive)
  3. Restart service after adding variables
  4. Use Railway CLI to verify:
    railway variables
    

Cost Optimization

Free Tier Limits

Railway free tier includes:

Cost Monitoring

Monitor usage in Railway dashboard:

  1. View "Usage" tab
  2. Check monthly spending
  3. Set up spending alerts

Optimization Tips

  1. Use Hobby Plan: For production, upgrade to Hobby plan ($5/month)
  2. Optimize Build: Use efficient Dockerfile to reduce build times
  3. Scale Appropriately: Start with minimal resources, scale as needed
  4. 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:

Rollback Strategy

If deployment fails:

  1. Railway automatically keeps previous deployment running
  2. Use Railway dashboard to rollback to previous deployment
  3. Fix issues and redeploy

Security Checklist

Before deploying to production:

Next Steps

Additional Resources