在 Railway 平台上部署应用。适用于部署容器化应用、设置数据库、配置私有网络或管理 Railway 项目。触发关键词:Railway, railway.app, deploy container, Railway database, 容器部署。
在 Railway 平台上部署和管理应用。
# 安装 Railway CLI
npm i -g @railway/cli
# 登录
railway login
# 初始化项目
railway init
# 部署
railway up
# 打开仪表盘
railway open
[build]
builder = "nixpacks" # 或 "railpack"(Nixpacks 的继任者)
buildCommand = "npm run build"
[deploy]
preDeployCommand = ["npm run db:migrate"] # 部署前命令
startCommand = "npm start"
healthcheckPath = "/health"
healthcheckTimeout = 300
restartPolicyType = "on_failure" # never | on_failure | always
restartPolicyMaxRetries = 3
cronSchedule = "*/15 * * * *" # 可选:定时任务
[service]
internalPort = 3000
{
"$schema": "https://railway.com/railway.schema.json",
"build": {
"builder": "NIXPACKS",
"buildCommand": "npm run build"
},
"deploy": {
"preDeployCommand": ["npm run db:migrate"],
"startCommand": "npm start",
"healthcheckPath": "/",
"healthcheckTimeout": 100,
"restartPolicyType": "on_failure",
"cronSchedule": "0 0 * * *"
}
}
# nixpacks.toml
[variables]
NODE_ENV = "production"
[phases.setup]
nixPkgs = ["nodejs-18_x", "python311"]
[phases.install]
cmds = ["npm ci --only=production"]
[phases.build]
cmds = ["npm run build"]
[start]
cmd = "npm start"
Railpack 是 Railway 新一代构建工具,提供更快的构建速度和更好的缓存机制。
# railpack.toml
[build]
command = "npm run build"
[start]
command = "npm start"
[cache]
paths = ["node_modules", ".next/cache"]
# 设置变量
railway variables set DATABASE_URL="postgres://..."
# 从文件设置
railway variables set < .env
# 链接到服务
railway service
railway variables set API_KEY="secret"
# 添加 PostgreSQL
railway add -d postgres
# 获取连接字符串
railway variables get DATABASE_URL
railway add -d redis
# 通过 REDIS_URL 访问
railway add -d mysql
# 通过 MYSQL_URL 访问
Railway 提供内部 DNS 用于服务间通信:
# 内部连接字符串格式
# Format: {service-name}.railway.internal:{port}
# PostgreSQL 私有网络连接