blog.dopana

Back

Railway là nền tảng deploy backend — kết nối GitHub repo, Railway build và host tự động.

Git push → Railway build → Deploy → HTTPS domain → Scale
plaintext

Không config server, không Dockerfile (optional), không quản lý infra.

Railway vs Các PaaS Khác#

HerokuRenderVercelFly.ioRailway
Free tier✅ ($5 credit)
Backend⚠️ Edge only
Frontend
DatabasePostgres (addon)Postgres, RedisPostgresPostgres, MySQL, Redis, MongoDB
Serverless
Private network
Volumes
Cron
Pricing$7+/tháng$7+/tháng$20+/tháng$5.68+/tháng$5+/tháng (usage-based)

Railway có lợi thế: database tích hợp, private network mặc định, usage-based pricing.

Quick Start#

# 1. Cài Railway CLI
npm i -g @railway/cli

# 2. Login
railway login

# 3. Init project trong thư mục code
railway init

# 4. Deploy
railway up

# Hoặc connect GitHub → auto-deploy khi push
bash

Deploy từ GitHub#

# railway.json — cấu hình project
{
  "build": {
    "builder": "NIXPACKS",
    "buildCommand": "npm run build"
  },
  "deploy": {
    "startCommand": "npm start",
    "healthcheckPath": "/health",
    "restartPolicyType": "ON_FAILURE"
  }
}
yaml
  1. New Project → Deploy from GitHub repo
  2. Chọn branch
  3. Railway auto-detect language + build
  4. Deploy + HTTPS domain tự động

Zero Config Detection#

LanguageBuildStart
Node.jsnpm ci && npm run buildnpm start
Pythonpip install -r requirements.txtpython main.py
Gogo build -o app./app
Rustcargo build --release./target/release/app
DockerDockerfileDockerfile CMD
StaticCopy filesN/A

Database Tích Hợp#

Railway có database plugins — click là có:

# CLI
railway add postgres
railway add mysql
railway add redis
railway add mongodb
bash
// DATABASE_URL tự động available
import postgres from 'postgres'

const sql = postgres(process.env.DATABASE_URL!)
// Railway tự động inject connection string
typescript
Plugin → Railway provision → Auto-inject DATABASE_URL

                        Code chỉ cần đọc env var
plaintext

Database có: backup tự động, metrics, scaling, private network.

Private Network#

Mọi service trong cùng project đều kết nối được qua private network:

Project
├── Web API (public)
├── Worker (private)
├── Postgres
└── Redis

Web API → private:5432 (Postgres)
Worker → private:6379 (Redis)
plaintext

Không expose database ra internet. Dùng DATABASE_URL thay DATABASE_PUBLIC_URL:

# DATABASE_URL — private network (nên dùng)
postgres://user:pass@db.railway.internal:5432/mydb

# DATABASE_PUBLIC_URL — public internet (không khuyến khích)
postgres://user:pass@db.railway.app:5432/mydb
bash

Private network = free egress. Public network = tính phí egress.

Environment & Variables#

# railway.toml — variables cho từng environment
[environments]
  [environments.production.variables]
  NODE_ENV = "production"
  LOG_LEVEL = "info"

  [environments.staging.variables]
  NODE_ENV = "staging"
  LOG_LEVEL = "debug"
bash
# Reference variables — dùng biến từ service khác
DATABASE_URL = "${{Postgres.DATABASE_URL}}"
REDIS_URL = "${{Redis.REDIS_URL}}"
bash

Volumes#

Persistent storage cho service cần giữ dữ liệu:

railway volume add --mount /data
bash
// Code đọc/ghi vào /data — persistent qua deploy
import fs from 'fs'

const data = fs.readFileSync('/data/config.json', 'utf-8')
fs.writeFileSync('/data/output.txt', 'persistent data')
typescript

Volumes có backup, snapshot, restore.

Pricing#

Railway tính phí theo usage (compute + egress):

PlanComputeEgress
Hobby$5 credit/tháng$5 credit/tháng
Pro$20 base + usage$0.10/GB
# $5 credit = chạy service nhỏ ~1 tháng
# Staging + Serverless = gần như free
bash

Usage limits: set hard limit để tránh overspend.

Cron#

{
  "cron": {
    "schedule": "0 0 * * *",
    "command": "npm run daily-report"
  }
}
json

Hoặc dùng CLI:

railway cron create --schedule "0 */6 * * *" --command "npm run sync"
bash

Railway Agent (AI)#

Railway tích hợp AI agent — chat với infrastructure:

"Deploy Postgres và kết nối với web API"
→ Railway Agent tự động provision + config
plaintext
railway agent "Scale web-api to 3 replicas"
railway agent "Add Redis and connect to worker"
railway agent "Show me recent errors in production"
bash

Use Cases#

Fullstack App#

Project
├── Next.js (frontend + API) — public
├── Postgres private
├── Redis private
└── Worker background job
bash

Microservices#

Project
├── api-gateway public
├── user-service private
├── payment-service private
├── notification-service private
├── Postgres private
└── Redis private
bash

Staging + Production#

railway environment create staging
# Deploy cùng code, database riêng
# Staging có Serverless = tiết kiệm
bash

Khi Nào Dùng Railway?#

✅ Nên dùng#

  • Backend API — Node, Python, Go, Rust, Docker
  • Fullstack app — frontend + backend + database cùng project
  • Microservices — private network mặc định
  • Starter / MVP — deploy nhanh, không config infra
  • Team nhỏ — không cần DevOps riêng

❌ Không nên#

  • Static site — Vercel/Cloudflare Pages rẻ hơn
  • Enterprise compliance — cần self-hosted
  • High-scale real-time — cần infra control nhiều hơn
  • Budget cực thấp — free tier hạn chế

Tổng Kết#

Railway là PaaS hiện đại — deploy nhanh, database tích hợp, private network, giá theo usage.

# Từ git push đến production: <5 phút
railway init
railway up
# → https://my-project.railway.app

# Thêm database: 1 click
railway add postgres
# → DATABASE_URL tự động inject
bash
Tính năngRailwayHerokuRender
DeployGit pushGit pushGit push
DatabaseBuilt-in (5 loại)Addon (trả thêm)Built-in (2 loại)
Private network✅ Mặc định
PricingUsage-based$7/tháng fixed$7/tháng fixed
Serverless✅ 1 click
AI Agent

Railway là lựa chọn tốt cho backend và fullstack app — đặc biệt khi cần database tích hợp và private network.

Tài liệu tham khảo#