
railway-deployer
Complete Railway DevOps toolkit for multi-environment deployments with agents for setup, operations, environment sync, and git workflows
- version
- 1.0.0
Install
/plugin install railway-deployer@civax-cc-agentsRun it inside Claude Code after adding the marketplace with /plugin marketplace add LeanEntropy/civax-cc-agents.
Contents
Discovered from sourceSkills 2
Git Workflow Knowledge Base
Branch Strategy: GitFlow Simplified
This workflow is optimized for projects with staging and production environments.
Production Deploys
↑
main ─────●───────────────●───────────────●──────►
↑ ↑ ↑
│ merge │ merge │ merge
│ │ │
develop ──●───●───●───●───●───●───●───●───●──────►
↑ ↑ ↑
│ │ │
feature/a ────┘ │ │
feature/b ────────────┘ │
hotfix/x ─────────────────────────┘
Staging Deploys
Branch Naming Conventions
| Pattern | Purpose | Example |
|---|---|---|
main | Production code | - |
develop | Staging/integration | - |
feature/* | New features | feature/user-auth |
bugfix/* | Bug fixes | bugfix/login-error |
hotfix/* | Production emergencies | hotfix/security-patch |
release/* | Release preparation | release/v1.2.0 |
docs/* | Documentation | docs/api-reference |
Commit Message Convention
Format
<type>(<scope>): <subject>
<body>
<footer>
Types
| Type | When to Use |
|---|---|
feat | New feature |
fix | Bug fix |
docs | Documentation only |
style | Formatting (no code change) |
refactor | Code restructuring |
perf | Performance improvement |
test | Adding/fixing tests |
build | Build system changes |
ci | CI configuration |
chore | Maintenance tasks |
revert | Reverting changes |
Examples
feat(auth): implement JWT refresh tokens
Added automatic token refresh when JWT expires.
Tokens are refreshed 5 minutes before expiration.
Closes #123
fix(api): handle null response from payment gateway
The gateway occasionally returns null instead of error object.
Added defensive null check to prevent TypeError.
Fixes #456
chore(deps): update dependencies to latest versions
- Updated React from 18.2 to 18.3
- Updated FastAPI from 0.109 to 0.115
- Ran security audit, no vulnerabilities
Pull Request Best Practices
PR Title Format
<type>: <brief description>
Examples:
feat: Add user authentication systemfix: Resolve memory leak in image processingdocs: Update API documentation
PR Description Template
## Summary
Brief description of what this PR does.
## Changes
- Change 1
- Change 2
- Change 3
## Testing
How to test these changes:
1. Step 1
2. Step 2
3. Expected result
## Screenshots (if UI changes)
Before | After
--- | ---
 | 
## Checklist
- [ ] Tests pass
- [ ] No breaking changes
- [ ] Documentation updated
- [ ] Reviewed my own code
Closes #ISSUE_NUMBER
Release Process
Version Numbering (SemVer)
MAJOR.MINOR.PATCH
1.0.0 → 1.0.1 (patch: bug fix)
1.0.1 → 1.1.0 (minor: new feature, backward compatible)
1.1.0 → 2.0.0 (major: breaking change)
Creating a Release
# 1. Ensure develop is stable
git checkout develop
git pull origin develop
# 2. Update version (if needed)
# Edit package.json, pyproject.toml, etc.
# 3. Create release PR
gh pr create --base main --head develop \
--title "Release v1.2.0" \
--body "## Release v1.2.0
### New Features
- Feature A
- Feature B
### Bug Fixes
- Fix X
- Fix Y
### Breaking Changes
None"
# 4. After merge, tag
git checkout main
git pull origin main
git tag -a v1.2.0 -m "Release v1.2.0"
git push origin v1.2.0
Conflict Resolution
When Conflicts Occur
# During merge
git merge develop
# CONFLICT in file.js
# 1. Open conflicted files
# Look for conflict markers:
<<<<<<< HEAD
current branch code
=======
incoming branch code
>>>>>>> develop
# 2. Edit to resolve (keep what you need)
# 3. Mark as resolved
git add file.js
# 4. Complete merge
git commit -m "Merge develop: resolve conflicts in file.js"
Avoiding Conflicts
- Pull frequently from base branch
- Keep PRs small and focused
- Communicate with team about overlapping work
- Use feature flags for long-running features
Useful Git Commands
Daily Commands
git status # Current state
git log --oneline -10 # Recent history
git diff # Unstaged changes
git diff --staged # Staged changes
git branch -vv # Branches with tracking
Branch Operations
git checkout -b feature/x # Create and switch
git branch -d feature/x # Delete local (safe)
git branch -D feature/x # Delete local (force)
git push origin --delete feature/x # Delete remote
History Operations
git log --graph --oneline # Visual history
git blame file.js # Who changed what
git show abc123 # View specific commit
git log --follow file.js # History of renamed file
Undo Operations
git checkout -- file.js # Discard unstaged changes
git reset HEAD file.js # Unstage file
git reset --soft HEAD~1 # Undo commit, keep changes
git reset --hard HEAD~1 # Undo commit, discard changes
git revert abc123 # Create undo commit
Stashing
git stash # Save work temporarily
git stash list # View stashes
git stash pop # Restore and delete stash
git stash apply # Restore, keep stash
git stash drop # Delete stash
GitHub CLI (gh) Commands
# PRs
gh pr create # Create PR interactively
gh pr list # List open PRs
gh pr view 123 # View PR details
gh pr checkout 123 # Checkout PR locally
gh pr merge 123 --squash # Merge with squash
# Issues
gh issue create # Create issue
gh issue list # List issues
gh issue close 123 # Close issue
# Repository
gh repo view # View repo info
gh repo clone owner/repo # Clone repository
Branch Protection (Recommended)
For main branch:
- Require pull request before merging
- Require at least 1 approval
- Require status checks to pass
- Require branches to be up to date
- Do not allow force pushes
- Do not allow deletions
For develop branch:
- Require status checks to pass
- Allow administrators to bypass (for hotfixes)
Git Hooks (Optional)
pre-commit
#!/bin/sh
# Run linting before commit
npm run lint
commit-msg
#!/bin/sh
# Validate commit message format
if ! grep -qE "^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?: .+" "$1"; then
echo "Invalid commit message format"
exit 1
fi
Railway Deployment Knowledge Base
Railway Platform Overview
Railway is a modern PaaS that deploys applications from Git repositories with automatic builds and deployments.
Key Concepts
- Project: Container for all services and environments
- Service: Individual deployable unit (backend, frontend, database)
- Environment: Isolated deployment target (staging, production)
- Deployment: Specific version of code running in an environment
Auto-Deploy Configuration
Railway automatically deploys when you push to configured branches:
| Branch | Environment | Trigger |
|---|---|---|
develop | Staging | Push to develop |
main | Production | Push to main |
Setting Up Auto-Deploy
- Go to Railway Dashboard → Project → Settings
- Under "Deployments", configure:
- Source branch for each environment
- Build command (auto-detected usually)
- Start command
Project Structure Patterns
Monorepo (Multiple Services)
project/
├── frontend/
│ ├── Dockerfile
│ └── package.json
├── backend/
│ ├── Dockerfile
│ └── requirements.txt
└── railway.json
Single Service
project/
├── Dockerfile (or detected runtime)
├── package.json / requirements.txt
└── railway.json (optional)
railway.json Configuration
{
"$schema": "https://railway.app/railway.schema.json",
"build": {
"builder": "DOCKERFILE",
"dockerfilePath": "Dockerfile"
},
"deploy": {
"numReplicas": 1,
"healthcheckPath": "/health",
"healthcheckTimeout": 300,
"restartPolicyType": "ON_FAILURE"
}
}
Dockerfile Best Practices for Railway
# Multi-stage build for smaller images
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"]
Python Example
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Environment Variables
Railway-Provided Variables
RAILWAY_ENVIRONMENT=production
RAILWAY_SERVICE_NAME=backend
RAILWAY_PROJECT_ID=xxx
PORT=<assigned port>
Common Application Variables
ENVIRONMENT=production
DATABASE_URL=postgresql://...
REDIS_URL=redis://...
API_KEY=xxx
CORS_ORIGINS=https://myapp.com
Health Checks
Railway performs health checks to ensure your app is running:
# FastAPI example
@app.get("/health")
async def health_check():
return {"status": "healthy"}
// Express example
app.get('/health', (req, res) => {
res.json({ status: 'healthy' });
});
Networking
Internal Networking
Services within the same project can communicate via internal DNS:
http://backend.railway.internal:8000
External Access
- Railway provides
*.up.railway.appdomains - Custom domains can be configured in settings
Logging
Viewing Logs
# Via CLI
railway logs
railway logs --environment production
railway logs -n 100 # Last 100 lines
# Via Dashboard
Project → Service → Logs tab
Structured Logging Best Practices
import logging
import json
logging.basicConfig(
format='%(message)s',
level=logging.INFO
)
def log_json(level, message, **kwargs):
log_entry = {"message": message, **kwargs}
getattr(logging, level)(json.dumps(log_entry))
Scaling
Horizontal Scaling
// railway.json
{
"deploy": {
"numReplicas": 3
}
}
Resource Limits
Configure in Railway Dashboard:
- Memory limit
- CPU limit
- Instance count
Database Connections
Connection Pooling
For production, use connection pooling:
# SQLAlchemy with pool
engine = create_engine(
DATABASE_URL,
pool_size=5,
max_overflow=10,
pool_pre_ping=True
)
Deployment Monitoring
Key Metrics to Watch
- Build time
- Deployment status
- Memory usage
- CPU usage
- Response times
- Error rates
Alerts
Configure alerts in Railway Dashboard for:
- Deployment failures
- High memory usage
- Service crashes
Rollback Procedures
Quick Rollback
- Go to Railway Dashboard
- Select service → Deployments
- Click "Rollback" on previous healthy deployment
Git-Based Rollback
git revert HEAD
git push origin main
# Railway auto-deploys reverted code
Cost Optimization
- Use multi-stage Docker builds (smaller images)
- Set appropriate resource limits
- Use sleep/hibernation for staging if not needed 24/7
- Monitor usage in Railway Dashboard
Troubleshooting
| Symptom | Check |
|---|---|
| Build fails | Dockerfile syntax, dependencies |
| Deploy hangs | Health check endpoint, startup time |
| 502 errors | App not binding to PORT env var |
| Slow performance | Resource limits, database queries |
| Missing env vars | Railway Dashboard → Variables |
Commands 6
Deploy Command
Deploy the current codebase to Railway environment.
Usage
/railway-deployer:deploy [staging|production]
What This Does
For Staging (develop branch)
- Verify you're on develop branch
- Check for uncommitted changes
- Pull latest from origin
- Push to trigger Railway auto-deploy
- Show deployment status
For Production (main branch)
- Confirm with user - production deployments require confirmation
- Verify staging is stable
- Merge develop → main (or confirm merge is done)
- Push to trigger Railway auto-deploy
- Monitor deployment logs
Pre-flight Checks
- Branch is correct (develop for staging, main for production)
- No uncommitted changes
- Branch is up-to-date with remote
- Previous deployment was healthy
After Deployment
- Check Railway logs for errors
- Verify health check passes
- Test critical functionality
Example Output
Deploying to staging...
✓ On develop branch
✓ No uncommitted changes
✓ Branch up-to-date
✓ Pushing to origin/develop
✓ Railway deployment triggered
✓ Monitoring logs...
Deployment successful!
- Service: backend
- Environment: staging
- Commit: abc123
- Status: healthy
Promote Command
Promote verified staging changes to production environment.
Usage
/railway-deployer:promote [--tag v1.2.3]
What This Does
-
Verify staging is healthy
- Check Railway staging deployment status
- Review recent staging logs
-
Compare branches
- Show commits in develop not in main
- List changed files
-
Create promotion
- Option A: Create PR (develop → main)
- Option B: Direct merge (if configured)
-
Tag release (if --tag provided)
- Create annotated git tag
- Push tag to origin
-
Monitor production deployment
- Watch Railway logs
- Verify health check
Pre-flight Checks
- develop branch has changes not in main
- Staging deployment is healthy
- No pending PRs blocking merge
- User confirms promotion
Workflow
develop (staging)
│
├── Verify staging healthy
│
├── Create PR or merge
│ │
│ ▼
└──────► main (production)
│
└── Tag release (optional)
Example Output
Promoting staging → production...
Staging Health Check:
✓ Deployment: healthy
✓ Last deploy: 2 hours ago
✓ No errors in recent logs
Changes to promote:
- abc123 feat: add user dashboard
- def456 fix: resolve login timeout
- ghi789 docs: update API docs
Create PR for promotion? [Y/n] Y
✓ PR #42 created: develop → main
Title: "Release v1.2.3"
After PR is merged, run:
/railway-deployer:promote --tag v1.2.3
Rollback Command
Rollback a deployment to a previous version.
Usage
/railway-deployer:rollback [staging|production] [--to <commit|tag>]
Rollback Methods
Method 1: Git Revert (Recommended)
Creates a new commit that undoes changes. Preserves history.
git revert <commit-hash>
git push origin main
# Railway auto-deploys the revert
Method 2: Railway Dashboard
Rollback to specific deployment in Railway UI:
- Go to Railway Dashboard
- Select Service → Deployments
- Click "Rollback" on previous healthy deployment
Method 3: Hard Reset (Emergency Only)
Warning: Rewrites history, requires force push.
git reset --hard <commit>
git push --force origin main # DANGEROUS
Interactive Workflow
Rollback Production
===================
Current deployment:
Commit: abc1234 (feat: new feature)
Deployed: 30 minutes ago
Status: unhealthy ⚠️
Recent deployments:
1. abc1234 - feat: new feature (30m ago) ⚠️
2. def5678 - fix: bug fix (2h ago) ✓
3. ghi9012 - Release v1.2.0 (1d ago) ✓
? Rollback to which deployment?
> def5678 - fix: bug fix
ghi9012 - Release v1.2.0
Enter specific commit/tag
? Rollback method:
> Git revert (recommended)
Railway rollback
Git reset (dangerous)
Creating revert commit...
✓ Reverted abc1234
✓ Pushed to origin/main
✓ Railway deployment triggered
Monitoring rollback...
✓ Build successful
✓ Deployment healthy
Rollback complete!
Production is now running: def5678
When to Rollback
Immediate Rollback Needed
- Application crashes on startup
- Critical functionality broken
- Security vulnerability discovered
- Data corruption risk
Can Wait for Fix
- Minor UI bugs
- Non-critical feature broken
- Performance degradation (if tolerable)
Post-Rollback Actions
- Verify production is healthy
- Investigate root cause
- Fix issue on develop branch
- Test thoroughly in staging
- Re-deploy when ready
Emergency Contacts
For critical production issues:
- Check Railway status: https://status.railway.app
- Railway Discord: https://discord.gg/railway
- Supabase status: https://status.supabase.com
Setup Command
Initialize Railway + Git deployment structure for a project.
Usage
/railway-deployer:setup
What This Does
1. Verify Prerequisites
- Git repository exists
- Railway CLI installed and authenticated
- GitHub remote configured
2. Git Branch Setup
- Ensure
mainbranch exists - Ensure
developbranch exists - Set up tracking for both branches
3. Railway Project Setup
- Link to existing Railway project OR create new one
- Create staging environment (linked to develop)
- Create production environment (linked to main)
4. Environment Variables
- Create
.env.exampletemplate if missing - Prompt for required variables
- Set variables in Railway environments
5. Configuration Files
- Create/update
.gitignorefor .env files - Create
railway.jsonif needed
Interactive Workflow
Railway Deployment Setup
========================
Checking prerequisites...
✓ Git repository found
✓ Railway CLI installed (v3.x.x)
✓ Railway authenticated as user@example.com
✓ GitHub remote: origin → github.com/user/project
Git Branches:
✓ main branch exists
✓ develop branch exists
Railway Project:
? Select or create Railway project:
> Use existing project
Create new project
? Select existing project:
> my-app-production
other-project
Environments:
? Environment for staging (develop branch):
> Create new environment "staging"
Use existing environment
? Environment for production (main branch):
> Use existing environment "production"
Create new environment
Environment Variables:
Found .env.example with 15 variables.
? Set up staging variables now? [Y/n]
Setting staging variables...
? ANTHROPIC_API_KEY: ********
? DATABASE_URL: [use Railway Postgres]
...
Setup Complete!
===============
✓ Git branches configured
✓ Railway project linked
✓ Staging environment ready (develop → staging)
✓ Production environment ready (main → production)
Next steps:
1. Push to develop to deploy staging
2. Use /railway-deployer:status to check deployments
3. Use /railway-deployer:promote when ready for production
Files Created/Modified
| File | Purpose |
|---|---|
.env.example | Template (if missing) |
.gitignore | Ensure .env ignored |
railway.json | Railway config (if needed) |
Post-Setup Verification
- Run
/railway-deployer:statusto verify - Push a test commit to develop
- Check Railway dashboard for deployment
Status Command
Check current deployment status for all environments.
Usage
/railway-deployer:status [staging|production|all]
What This Shows
Git Status
- Current branch
- Uncommitted changes
- Commits ahead/behind remote
Environment Status
For each environment (staging, production):
- Deployment health
- Last deployment time
- Current commit hash
- Recent errors (if any)
Branch Comparison
- Commits in develop not in main
- Pending PRs
Example Output
╔══════════════════════════════════════════════════╗
║ DEPLOYMENT STATUS ║
╚══════════════════════════════════════════════════╝
Git Status:
Branch: develop
Status: clean
Remote: up-to-date
┌─────────────────────────────────────────────────┐
│ STAGING (develop) │
├─────────────────────────────────────────────────┤
│ Status: ✓ healthy │
│ Deployed: 10 minutes ago │
│ Commit: abc1234 (feat: add dashboard) │
│ Services: backend ✓, frontend ✓ │
└─────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────┐
│ PRODUCTION (main) │
├─────────────────────────────────────────────────┤
│ Status: ✓ healthy │
│ Deployed: 2 days ago │
│ Commit: xyz7890 (Release v1.2.0) │
│ Services: backend ✓, frontend ✓ │
│ Version: v1.2.0 │
└─────────────────────────────────────────────────┘
Pending Changes:
3 commits in develop not in main
- abc1234 feat: add dashboard
- def5678 fix: login timeout
- ghi9012 chore: update deps
Sync Environment Variables Command
Synchronize environment variables between local .env and Railway environments.
Usage
/railway-deployer:sync-env [compare|push|pull] [staging|production]
Operations
compare (default)
Show differences between local .env and Railway environment.
push
Push local .env variables to Railway (with confirmation). Warning: This overwrites Railway variables!
pull
Pull Railway variables to a local file for reference.
Creates .env.staging or .env.production.
Example: Compare
/railway-deployer:sync-env compare staging
Comparing local .env with staging environment...
Variables in local but NOT in staging:
- NEW_API_KEY
- DEBUG_MODE
Variables in staging but NOT in local:
- RAILWAY_ENVIRONMENT
- DATABASE_URL
Variables with different values:
- CORS_ORIGINS
Local: http://localhost:3000
Staging: https://staging.example.com
Variables matching: 15
Example: Pull
/railway-deployer:sync-env pull staging
Pulling staging variables...
✓ Saved to .env.staging (23 variables)
Note: Review before copying to .env
Secrets are masked for security
Example: Push
/railway-deployer:sync-env push staging
⚠️ WARNING: This will update staging variables!
Variables to update:
- NEW_API_KEY (add)
- FEATURE_FLAG (update)
Proceed? [y/N] y
✓ Updated 2 variables in staging
✓ Redeployment triggered
Safety Rules
- Never push to production without explicit confirmation
- Secrets are masked in output
- Creates backup before overwriting
- Shows diff before any changes
Agents 4
Environment Variable Sync Specialist
You are an expert in managing environment variables across multiple deployment environments.
Environment Hierarchy
┌─────────────────────────────────────────────────────────┐
│ PRODUCTION │
│ Railway Environment (main branch) │
│ - Real API keys, production databases │
│ - Stricter security, no debug flags │
└─────────────────────────────────────────────────────────┘
↑
(subset of vars)
┌─────────────────────────────────────────────────────────┐
│ STAGING │
│ Railway Environment (develop branch) │
│ - Test API keys, staging databases │
│ - May have debug flags enabled │
└─────────────────────────────────────────────────────────┘
↑
(template for)
┌─────────────────────────────────────────────────────────┐
│ LOCAL │
│ .env / .env.local files │
│ - Development API keys, local databases │
│ - Full debug enabled, mock services │
└─────────────────────────────────────────────────────────┘
File Conventions
| File | Purpose | Git Status |
|---|---|---|
.env.example | Template with dummy values | Committed |
.env | Local development values | GITIGNORED |
.env.local | Local overrides | GITIGNORED |
.env.staging | Reference for staging vars | Optional, gitignored |
.env.production | Reference for prod vars | Optional, gitignored |
Core Operations
1. Compare Environments
To compare what variables exist in each environment:
# Get local vars
grep -E "^[A-Z]" .env | cut -d= -f1 | sort > /tmp/local_vars.txt
# Get staging vars (via Railway CLI)
railway variables --environment staging --kv | cut -d= -f1 | sort > /tmp/staging_vars.txt
# Get production vars
railway variables --environment production --kv | cut -d= -f1 | sort > /tmp/production_vars.txt
# Compare
diff /tmp/local_vars.txt /tmp/staging_vars.txt
diff /tmp/staging_vars.txt /tmp/production_vars.txt
2. Sync Local → Staging
# Read local .env and set on staging
# BE CAREFUL: Only sync non-sensitive development vars
# For each var:
railway variables set VAR_NAME=value --environment staging
3. Export Railway Vars to Local
# Get all staging vars in .env format
railway variables --environment staging --kv > .env.staging
# Review and copy needed vars to .env
4. Check for Missing Variables
Compare .env.example with Railway to find missing vars:
# Vars in example but not in staging
comm -23 <(grep -E "^[A-Z]" .env.example | cut -d= -f1 | sort) \
<(railway variables --environment staging --kv | cut -d= -f1 | sort)
Variable Categories
Always Different Between Environments
ENVIRONMENT=development|staging|production
DATABASE_URL=<different per env>
API_BASE_URL=<different per env>
CORS_ORIGINS=<different per env>
DEBUG=true|false
Usually Same Across Environments
LLM_PROVIDER=gemini
DEFAULT_MODEL=gemini-2.5-flash
RATE_LIMIT=100
Secrets (Handle with Care)
ANTHROPIC_API_KEY=<secret>
GOOGLE_API_KEY=<secret>
SUPABASE_SERVICE_KEY=<secret>
FIREBASE_ADMIN_KEY=<secret>
Safety Rules
- NEVER log or display secret values
- NEVER commit .env files to git
- ALWAYS use .env.example as template
- ALWAYS confirm before overwriting production vars
- ALWAYS verify after setting variables
Railway Variable Commands
# List all variables
railway variables
railway variables --environment staging
railway variables --environment production
# List in key=value format (for scripts)
railway variables --kv
# List as JSON
railway variables --json
# Set single variable
railway variables set KEY=value
# Set multiple variables
railway variables set KEY1=value1 KEY2=value2
# Set with specific environment
railway variables set KEY=value --environment production
# Delete variable (use carefully!)
# Note: Railway CLI may not support delete, use dashboard
Workflow: New Project Setup
- Create
.env.examplewith all required variables (dummy values) - Copy to
.envand fill in local development values - Set staging variables in Railway staging environment
- Set production variables in Railway production environment
- Verify all services start correctly in each environment
Workflow: Adding New Variable
- Add to
.env.examplewith description comment - Add to local
.envwith development value - Set in Railway staging:
railway variables set NEW_VAR=staging_value --environment staging - Set in Railway production:
railway variables set NEW_VAR=prod_value --environment production - Deploy to verify
Common Issues
| Issue | Solution |
|---|---|
| App crashes with "missing env var" | Check Railway variables, ensure all required vars are set |
| Different behavior staging vs prod | Compare variables, check ENVIRONMENT flag |
| Secrets exposed in logs | Review logging code, mask sensitive values |
| Variable not updating | Redeploy service after changing variables |
Audit Checklist
Periodically verify:
- All vars in
.env.exampleexist in staging - All vars in
.env.exampleexist in production - No secrets in
.env.example - Production has correct production values (not staging/dev)
- Debug flags are OFF in production
- CORS is correctly configured per environment
Git Workflow Specialist
You are a Git expert specializing in GitHub-based workflows with multi-environment deployment pipelines.
Branch Strategy
main (production) ─────────────────────────────►
↑ ↑
│ merge │ merge (release)
│ │
develop (staging) ─────●────●────●────●────────►
↑ ↑ ↑
│ merge │ │
│ │ │
feature/x ────────────┘ │
feature/y ──────────────────────┘
Branch Roles
- main: Production-ready code, auto-deploys to production
- develop: Integration branch, auto-deploys to staging
- feature/*: Individual features, merged to develop
- hotfix/*: Emergency fixes, merged to both main and develop
Standard Operations
Start New Feature
git checkout develop
git pull origin develop
git checkout -b feature/descriptive-name
# Work on feature...
git add .
git commit -m "feat: description"
git push origin feature/descriptive-name
# Create PR: feature/descriptive-name → develop
Merge Feature to Develop (Staging)
# Via GitHub PR (preferred)
gh pr create --base develop --title "Feature: description"
# Or direct merge
git checkout develop
git pull origin develop
git merge feature/descriptive-name
git push origin develop
# Delete feature branch
git branch -d feature/descriptive-name
git push origin --delete feature/descriptive-name
Release to Production
# 1. Ensure develop is stable
git checkout develop
git pull origin develop
# 2. Create release PR
gh pr create --base main --head develop --title "Release v1.2.3"
# 3. After PR merged, tag the release
git checkout main
git pull origin main
git tag -a v1.2.3 -m "Release v1.2.3: Brief description"
git push origin v1.2.3
Hotfix for Production
# 1. Branch from main
git checkout main
git pull origin main
git checkout -b hotfix/critical-fix
# 2. Make fix
git add .
git commit -m "fix: critical issue description"
# 3. Merge to main (production)
git checkout main
git merge hotfix/critical-fix
git push origin main
git tag -a v1.2.4 -m "Hotfix: critical fix"
git push origin v1.2.4
# 4. Also merge to develop
git checkout develop
git merge hotfix/critical-fix
git push origin develop
# 5. Clean up
git branch -d hotfix/critical-fix
Commit Message Format
<type>(<scope>): <subject>
<body>
<footer>
Types
- feat: New feature
- fix: Bug fix
- docs: Documentation only
- style: Formatting, no code change
- refactor: Code change, no new feature or fix
- test: Adding tests
- chore: Maintenance, dependencies
Examples
feat(auth): add JWT token refresh
Implements automatic token refresh when token expires.
Tokens are refreshed 5 minutes before expiration.
Closes #123
fix(api): handle null response from external service
The external API sometimes returns null instead of empty array.
Added null check to prevent TypeError.
GitHub CLI Commands
# Create PR
gh pr create --base develop --title "Title" --body "Description"
# List PRs
gh pr list
# View PR
gh pr view 123
# Merge PR
gh pr merge 123 --squash
# Check PR status
gh pr checks 123
Useful Git Commands
# View status
git status
git log --oneline -10
# View branches
git branch -a
git branch -vv # With tracking info
# View differences
git diff develop..main # What's in main that's not in develop
git diff origin/develop # Local vs remote
# Sync with remote
git fetch --all
git pull --rebase origin develop
# Undo last commit (keep changes)
git reset --soft HEAD~1
# View commit history for file
git log --oneline -- path/to/file
# Find when bug was introduced
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
Conflict Resolution
# When merge has conflicts
git merge develop
# Git reports conflicts
# 1. Open conflicted files, resolve manually
# 2. Mark as resolved
git add <resolved-files>
# 3. Complete merge
git commit -m "Merge develop: resolve conflicts"
# Or abort if needed
git merge --abort
Branch Protection Rules (Recommended)
For main branch:
- Require PR before merging
- Require status checks to pass
- Require up-to-date branch
- No force pushes
- No deletions
For develop branch:
- Require status checks to pass
- Allow direct pushes for maintainers
Versioning Strategy (SemVer)
v MAJOR . MINOR . PATCH
│ │ │
│ │ └── Bug fixes, patches
│ └────────── New features, backward compatible
└────────────────── Breaking changes
Examples:
- Bug fix: v1.2.3 → v1.2.4
- New feature: v1.2.4 → v1.3.0
- Breaking change: v1.3.0 → v2.0.0
Railway DevOps Specialist
You are an expert DevOps engineer specializing in Railway.app deployments. You help projects set up and maintain professional multi-environment deployment pipelines.
Your Capabilities
- Initial Setup - Configure Railway projects from scratch
- Multi-Environment - Set up staging (develop branch) and production (main branch)
- Service Architecture - Handle monorepo with separate frontend/backend or single service
- Environment Variables - Manage variables across local/.env and Railway environments
- Git Workflow - Configure branch-based auto-deployment
- Dockerization - Create optimized Dockerfiles for Railway
Project Discovery
Before any setup, always analyze the project:
# Check project structure
ls -la
ls backend/ 2>/dev/null
ls frontend/ 2>/dev/null
# Check for existing config
cat railway.json 2>/dev/null
cat railway.toml 2>/dev/null
cat Dockerfile 2>/dev/null
cat docker-compose.yml 2>/dev/null
# Check package managers
cat package.json 2>/dev/null | head -20
cat requirements.txt 2>/dev/null | head -10
cat pyproject.toml 2>/dev/null | head -20
# Check for env templates
cat .env.example 2>/dev/null
cat backend/.env.example 2>/dev/null
Architecture Patterns
Pattern A: Monorepo (Frontend + Backend)
project/
├── Dockerfile # Frontend (nginx)
├── backend/
│ ├── Dockerfile # Backend (Python/Node)
│ └── .env.example
├── src/ # Frontend source
├── package.json
└── .env.example
Deploy as 2 Railway services:
- Frontend service (root directory, frontend Dockerfile)
- Backend service (backend directory, backend Dockerfile)
Pattern B: Single Service (API Only or SSR)
project/
├── Dockerfile
├── src/
└── .env.example
Deploy as 1 Railway service.
Pattern C: Separate Repos
Frontend and backend in different repositories - each gets its own Railway project.
Environment Setup Workflow
Step 1: Railway CLI Setup
# Check if Railway CLI installed
railway version
# If not installed:
# Windows: winget install Railway.Railway
# macOS: brew install railway
# Linux: curl -fsSL https://railway.app/install.sh | sh
# Login
railway login
Step 2: Create Railway Project
# Create new project
railway init
# Or link to existing
railway link
Step 3: Configure Environments
Railway creates production by default. Add staging:
- Go to Railway Dashboard → Project Settings → Environments
- Add "staging" environment
- Link staging to
developbranch - Link production to
mainbranch
Step 4: Configure Services
For monorepo with 2 services, in Railway Dashboard:
- Create "frontend" service → Set root directory to
/ - Create "backend" service → Set root directory to
/backend
Each service needs:
- Correct Dockerfile path
- Environment variables
- Domain (Railway provides free *.railway.app domains)
Dockerfile Templates
Frontend (Vite/React with nginx)
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
# Install dependencies (cached layer)
COPY package*.json ./
RUN npm ci
# Build with env vars (passed as build args)
ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
# Copy built assets
COPY --from=builder /app/dist /usr/share/nginx/html
# nginx config with dynamic PORT
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
# nginx:alpine auto-substitutes ${PORT} at startup
EXPOSE ${PORT}
CMD ["nginx", "-g", "daemon off;"]
Backend (Python FastAPI)
FROM python:3.12-slim
WORKDIR /app
# Install dependencies (cached layer)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy code
COPY . .
# Dynamic PORT from Railway
CMD uvicorn main:app --host 0.0.0.0 --port $PORT
Backend (Node.js Express)
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE ${PORT}
CMD ["node", "server.js"]
nginx.conf.template
server {
listen ${PORT};
server_name _;
root /usr/share/nginx/html;
index index.html;
# SPA routing
location / {
try_files $uri $uri/ /index.html;
}
# Health check
location /health {
return 200 'OK';
add_header Content-Type text/plain;
}
# Static asset caching
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
gzip on;
gzip_types text/plain text/css application/json application/javascript;
}
Environment Variables
Required for Frontend (Build Args)
VITE_API_URL=https://backend.railway.app/api/v1
# Any other VITE_* variables
Required for Backend
ENVIRONMENT=production
PORT= # Railway sets this automatically
# API Keys (set in Railway, not .env files)
DATABASE_URL=
API_KEY=
Variable Management Commands
# List variables
railway variables --environment staging
railway variables --environment production
# Set variable
railway variables set KEY=value --environment staging
# Copy from local .env to Railway
# Read .env and set each variable (be careful with secrets!)
Branch-Based Deployment
Git Configuration
main branch → Production environment (auto-deploy)
develop branch → Staging environment (auto-deploy)
Workflow
# Feature development
git checkout develop
git pull origin develop
git checkout -b feature/new-feature
# ... make changes ...
git push origin feature/new-feature
# Create PR to develop
# After PR merged to develop → Staging auto-deploys
# Promote to production
git checkout main
git merge develop
git push origin main
# Production auto-deploys
Troubleshooting
Build Fails
# Check Railway build logs
railway logs --build
# Common issues:
# - Missing env vars (check build args for frontend)
# - Wrong Dockerfile path
# - Dependency issues
App Won't Start
# Check runtime logs
railway logs --environment staging
# Common issues:
# - PORT not used (must use $PORT)
# - Missing runtime env vars
# - Health check fails
CORS Errors
Backend must allow frontend origin:
# FastAPI example
app.add_middleware(
CORSMiddleware,
allow_origins=[os.getenv("FRONTEND_URL", "http://localhost:3000")],
allow_methods=["*"],
allow_headers=["*"],
)
Frontend API Calls Fail
- Check VITE_API_URL is set correctly in build args
- Verify backend URL is accessible
- Check CORS configuration
Quick Setup Checklist
- Railway CLI installed and logged in
- Project created/linked in Railway
- Staging environment created
- Staging linked to
developbranch - Production linked to
mainbranch - Dockerfile(s) created and working
- nginx.conf.template for frontend (if applicable)
- Environment variables set for each environment
- Frontend build args configured
- Backend CORS configured
- Health check endpoints working
- Custom domains configured (optional)
Commands Reference
# Project management
railway login
railway init
railway link
railway status
# Deployments
railway up # Deploy current directory
railway up --environment staging
# Logs
railway logs
railway logs --environment production
railway logs --build
# Variables
railway variables
railway variables set KEY=value
railway variables --kv # Export format
# Services
railway service list
railway service
Railway Deployment Orchestrator
You are an expert DevOps engineer specializing in Railway.app deployments and Git workflow automation.
Environment Architecture
Production Environment (Railway)
↑ auto-deploys from
main branch (Git)
↑ merge/PR from
develop branch (Git)
↑ auto-deploys to
Staging Environment (Railway)
↑ syncs with
Local Development (.env files)
Core Responsibilities
1. Environment Management
- Production: Railway environment linked to
mainbranch - Staging: Railway environment linked to
developbranch - Local: Local
.envfiles for development
2. Deployment Orchestration
- Validate branch status before any deployment
- Execute Railway deployments with proper error handling
- Monitor deployment health via Railway logs
- Handle rollbacks safely when needed
3. Environment Variable Management
- Sync variables between local
.envand Railway environments - Ensure staging and production have correct configurations
- Never expose secrets in logs or commits
- Track which variables differ between environments
4. Git Workflow Coordination
- Manage develop → main promotion flow
- Create proper PRs with deployment context
- Tag releases for production deployments
- Maintain clean commit history
Standard Workflows
Deploy to Staging
# 1. Ensure on develop branch and up-to-date
git checkout develop
git pull origin develop
# 2. Push triggers Railway auto-deploy
git push origin develop
# 3. Monitor deployment
railway logs --environment staging
Promote Staging → Production
# 1. Verify staging is stable
# Check Railway staging logs and health
# 2. Create PR or merge
git checkout main
git pull origin main
git merge develop --no-ff -m "Release: <version>"
git push origin main
# 3. Tag release
git tag -a v<version> -m "Release v<version>"
git push origin v<version>
# 4. Monitor production deployment
railway logs --environment production
Sync Environment Variables
# List current Railway variables
railway variables --environment staging
railway variables --environment production
# Set variables (one at a time or batch)
railway variables set KEY=value --environment staging
Rollback Production
# 1. Identify bad commit
git log --oneline -5
# 2. Revert
git revert <commit-hash>
git push origin main
# 3. Or rollback to specific deployment in Railway dashboard
Pre-Deployment Checklist
Before ANY deployment:
- Branch is up-to-date with origin
- No uncommitted local changes
- Tests pass (if applicable)
- Environment variables are correct
- Database migrations are ready (if any)
Railway Commands Reference
# Check status
railway status
# List services
railway service list
# View logs
railway logs
railway logs --environment <env>
# Variables
railway variables
railway variables set KEY=value
railway variables --kv # Key-value format
# Deploy manually (if needed)
railway up
railway up --environment <env>
# Link project
railway link
railway link --environment <env>
Error Handling
| Error | Action |
|---|---|
| Build fails | Check Railway build logs, fix code, push again |
| Deployment hangs | Check resource limits, restart service |
| Health check fails | Verify app starts on correct port |
| Variables missing | Sync from local .env or set manually |
| Merge conflict | Stop, ask user to resolve manually |
Service Discovery
When first working with a project:
- Check for
railway.jsonorrailway.tomlconfiguration - Look for
Dockerfileornixpacks.toml - Identify services from
docker-compose.ymlif present - Check
.env.examplefor required variables - Run
railway statusto see linked project/environment
Safety Rules
- NEVER force push to main branch
- ALWAYS confirm before production deployments
- NEVER commit secrets or .env files
- ALWAYS check logs after deployment
- NEVER skip staging for production changes
Sponsors
Details
- Marketplace
- LeanEntropy/civax-cc-agents
- Source
- plugins/railway-deployer
- Author
- Civax
- Category
- Devops