Module 4 of 6
Cloud Deployment
Deploy from GitHub to Railway: services, databases, variables, secrets, build and start commands, migrations, logs and health checks.
0% · 0 of 17 lessons
Your application works locally and its code is on GitHub. In this module you will deploy it to Railway, a cloud platform that builds and runs applications and databases directly from a GitHub repository.
Railway application and database architecture
Users
GitHub
Railway project · production environment
Application service
PostgreSQL
Redis (optional)
Railway account creation
- Go to railway.com.
- Choose to log in or sign up with GitHub. This links your GitHub account, which Railway needs to deploy your repositories.
- Authorize Railway in the GitHub prompt.
- Review the plan and billing options on Railway's pricing page. Usage-based billing means costs depend on what you run — see Cost Calculator.
GitHub integration
For Railway to deploy a private repository, its GitHub app must be allowed to access that repository.
- When you first deploy from GitHub, Railway prompts you to install or configure the Railway GitHub app.
- You can grant access to all repositories or only selected repositories. Selecting specific repositories follows the principle of least privilege.
- If your repository does not appear later, adjust the app's repository access in GitHub settings under Applications.
Creating projects from repositories
A Railway project is a container for related services and environments.
- In the Railway dashboard, create a New Project.
- Choose the option to deploy from a GitHub repository.
- Select your repository.
- Railway creates an application service and starts the first build automatically.
The first deployment may fail if variables or a database are missing. That is normal — you will configure them next.
Application services
A service is a deployable unit: your web application, a database or a background worker. Each service has its own:
- Source (GitHub repository and branch, or a database image)
- Variables
- Build and deploy settings
- Logs
- Networking (public domain, private hostname)
Most MVPs need one application service and, optionally, one database service.
PostgreSQL, MongoDB and Redis
Railway can add database services to your project in a few clicks. Choose based on your data, not popularity.
PostgreSQL
A relational database that stores data in tables with defined columns and relationships.
- Use when: users, orders, tasks, invoices — structured records that relate to each other. The safe default for most business applications.
- Strengths: reliability, data integrity, powerful queries, transactions, mature tooling and migrations.
MongoDB
A document database that stores flexible JSON-like documents.
- Use when: records vary widely in shape, or the application naturally works with nested documents.
- Consider: relational data with many relationships is usually simpler in PostgreSQL.
Redis
An in-memory key-value store that is extremely fast.
- Use when: caching expensive results, storing sessions, rate limiting or background job queues.
- Consider: Redis complements a primary database. Do not use it as your only store for important data unless you understand its persistence settings.
When no database is necessary
Skip the database when the application:
- Serves static or file-based content (like this guide).
- Performs calculations without saving results.
- Stores only per-user preferences that can live in browser local storage.
No database means lower cost, simpler deployment and fewer failure points.
Adding a database
In your project, choose to add a new service and select the database type. Railway provisions it and exposes connection variables such as a connection URL on the database service.
Database reference variables
Your application needs the database connection string. Rather than copying it by hand, use a reference variable: a variable on the application service that points to a variable on the database service. Railway keeps it in sync if credentials change.
The syntax uses double curly braces with the service name. For a PostgreSQL service named Postgres, the application's variable would look like this:
DATABASE_URL=${{Postgres.DATABASE_URL}}The exact variable names on your database service are shown in its Variables tab. Railway's variable editor can also suggest references for you.
Environment variables
Environment variables hold configuration that varies between environments or must stay secret. Typical examples:
| Variable | Example purpose | Source |
|---|---|---|
DATABASE_URL | Database connection | Reference variable |
NODE_ENV | Production mode | Often set automatically by the platform or framework |
AUTH_SECRET | Signs session tokens | Generate yourself |
APP_URL | Public base URL of the app | Your Railway or custom domain |
STRIPE_SECRET_KEY | Third-party API key | The provider's dashboard |
Set them in the application service's Variables tab. Changing variables typically triggers a redeployment.
The .env.example file in your repository should list every required variable name with placeholder values, so you know exactly what to configure.
Secret management
To generate a strong random secret on macOS:
openssl rand -base64 32Build and start commands
Railway detects most common project types and determines how to build and start them automatically. For a Node.js project it typically:
- Installs dependencies.
- Runs the
buildscript frompackage.json. - Runs the
startscript.
You can override these in the service's build and deploy settings in the dashboard. Railway has also supported a railway.json / railway.toml configuration file committed to the repository.
{
"$schema": "https://railway.com/railway.schema.json",
"build": { "buildCommand": "npm run build" },
"deploy": {
"startCommand": "npm start",
"healthcheckPath": "/api/health"
}
}Database migrations
Migrations create and update database tables in a controlled, repeatable way. Your ORM generates migration files during development; those files are committed to Git and applied to the production database during deployment.
Common approaches on Railway:
- Pre-deploy command: run migrations before the new version starts, for example
npx prisma migrate deploy. If migrations fail, the deployment stops and the previous version keeps running. - Start command chaining:
npm run migrate && npm start. Simpler, but a failed migration crashes startup.
Private networking
Services in the same Railway project and environment can communicate over a private network using internal hostnames in the form service-name.railway.internal (use http://, not https://, internally). The private network is available while services run, not during the build. Older environments may resolve internal names over IPv6 only, so some libraries need IPv6-compatible settings — check Railway's private networking guide. Benefits:
- Database traffic does not travel over the public internet.
- Databases do not need public exposure.
- Private network traffic avoids public egress charges.
When you use a database's private connection variable as a reference, the application connects privately. Only expose a database publicly if you genuinely need to connect from outside Railway, and protect it with strong credentials.
Health checks
A health check is an endpoint Railway calls after deploying a new version. Railway waits until it responds successfully before switching traffic to the new deployment. If it never succeeds, the deployment fails and the previous version keeps serving users.
A minimal health check endpoint returns a success status and no sensitive information:
// app/api/health/route.ts (Next.js example)
export function GET() {
return Response.json({ status: "ok" });
}Configure the path, such as /api/health, in the service's deploy settings. Railway accepts any 2xx response, uses the PORT variable it provides, and waits up to five minutes by default. Health check requests come from the hostname healthcheck.railway.app, so applications that restrict allowed hostnames must permit it. Health checks only gate a new deployment; they do not monitor the application afterwards.
Build logs and runtime logs
Railway provides two kinds of logs for each deployment:
- Build logs: dependency installation and the build command. Failures here mean the deployment never starts. Look for the first error, not the last line.
- Deploy (runtime) logs: output from your running application. Failures here include crashes, database connection errors and missing variables.
When something fails:
- Open the failed deployment and read the relevant log.
- Copy the error and roughly 20 lines of context.
- Remove secrets.
- Paste into ChatGPT with the troubleshooting prompt below.
Railway Deployment Troubleshooting
- Purpose
- Diagnose a failed or unhealthy Railway deployment from its logs and get a targeted fix.
- When to use
- When a Railway build fails, the deployment crashes, the health check fails or the application returns errors.
[BUILD OR RUNTIME][PASTE RELEVANT LOG LINES][VARIABLE NAMES SET, NOT VALUES][WHAT CHANGED SINCE THE LAST SUCCESSFUL DEPLOYMENT]My Railway deployment is failing. Help me find the root cause. ## Failure type [BUILD OR RUNTIME] failure ## Relevant log lines (secrets removed) ``` [PASTE RELEVANT LOG LINES] ``` ## Environment variable names configured on the service (values omitted) [VARIABLE NAMES SET, NOT VALUES] ## What changed since the last successful deployment [WHAT CHANGED SINCE THE LAST SUCCESSFUL DEPLOYMENT] ## Please provide 1. The most likely root cause and how confident you are. 2. How to confirm it using Railway logs, variables or settings. 3. Whether the fix is a Railway configuration change or a source code change. 4. For configuration changes: exact steps and values to check, without inventing secrets. 5. For source code changes: one consolidated Claude Code corrective prompt that starts with LOW GAS operating instructions, includes the error evidence, requires a regression test where practical, requires tests and a production build, and requires committing and pushing without force-pushing. 6. How to verify the fix after redeployment.
Common deployment failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Build fails on type errors | Code that runs in development fails strict production build | Run npm run build locally, fix with Claude Code |
Cannot find module | Dependency missing from package.json or wrong case in import path | Add dependency; macOS ignores file name case, Linux does not |
| Application unreachable | Not listening on PORT, or listening only on localhost | Use PORT; bind to all interfaces if the framework requires it |
| Health check fails | Wrong path, slow startup or crash | Check path and runtime logs |
| Database connection refused | Missing or wrong DATABASE_URL reference | Check reference variable and service name |
| Missing environment variable | Variable not set on the application service | Compare against .env.example |
| Works locally, not in production | Different variables, Node version or case-sensitive paths | Compare environments, pin Node version |
See Troubleshooting for more.
Automatic versus controlled deployment
By default, Railway redeploys whenever you push to the connected branch. This is fast but means every push to main reaches users.
| Approach | How | When |
|---|---|---|
| Automatic | Push to main deploys | Solo projects, early stages, with local testing discipline |
| Wait for CI | Railway deploys only after GitHub checks pass | When you have automated tests in GitHub Actions |
| Branch-based | Develop on feature branches; merge to main only when validated | Any application with real users |
| Staging environment | A separate Railway environment deploys a staging branch first | Higher-risk changes, teams |
Railway configuration prompt
Use this ChatGPT prompt before your first deployment to determine every setting your application needs.
Railway Deployment Configuration
- Purpose
- Determine exactly how to configure Railway for your application before the first deployment.
- When to use
- When the application runs locally and is pushed to GitHub, before creating the Railway project.
[PASTE README.md AND package.json OR EQUIVALENT][DATABASE: none, PostgreSQL, MongoDB, Redis][PASTE .env.example][CUSTOM DOMAIN, if any]I am deploying my application to Railway from a private GitHub repository. Help me configure it correctly. ## Project details [PASTE README.md AND package.json OR EQUIVALENT] ## Database [DATABASE: none, PostgreSQL, MongoDB, Redis] ## Environment variables required (.env.example — names and placeholders only) [PASTE .env.example] ## Custom domain [CUSTOM DOMAIN, if any] ## Please provide 1. The Railway services I need and how to create them, step by step. 2. Every environment variable to set on the application service, including which ones should use Railway reference variables (for example a database URL referencing the database service) and which ones I must generate myself. Explain how to generate secure secret values. Never invent real secret values. 3. The build command and start command, and whether Railway can detect them automatically. 4. How the application must listen on the PORT variable that Railway provides. 5. Database migration procedure and where to run it (for example a pre-deploy command). 6. Whether private networking should be used between services. 7. A health check path, if appropriate. 8. Any changes the source code needs before deployment. If changes are needed, write a single consolidated Claude Code prompt that starts with LOW GAS operating instructions, requires tests and a production build, and requires committing and pushing without force-pushing. 9. A post-deployment validation checklist. Note that Railway's interface may differ from your training data. Tell me what to look for rather than claiming exact button positions.
Module 4 checklist
0 of 10 complete