database

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Database

数据库

Add official Railway database services. These are maintained templates with pre-configured volumes, networking, and connection variables.
For non-database templates, see the
templates
skill.
添加官方Railway数据库服务。这些是经过维护的模板,带有预配置的存储卷、网络和连接变量。
对于非数据库模板,请查看
templates
Skill。

When to Use

使用场景

  • User asks to "add a database", "add Postgres", "add Redis", etc.
  • User needs a database for their application
  • User asks about connecting to a database
  • User says "add postgres and connect to my server"
  • User says "wire up the database"
  • 用户要求“添加数据库”“添加Postgres”“添加Redis”等
  • 用户的应用程序需要数据库
  • 用户询问如何连接数据库
  • 用户说“add postgres and connect to my server”
  • 用户说“wire up the database”

Decision Flow

决策流程

ALWAYS check for existing databases FIRST before creating.
User mentions database
  Check existing DBs first
  (query env config for source.image)
   ┌────┴────┐
 Exists    Doesn't exist
    │           │
    │      Create database
    │      (CLI or API)
    │           │
    │      Wait for deployment
    │           │
    └─────┬─────┘
    User wants to
    connect service?
    ┌─────┴─────┐
   Yes         No
    │           │
Wire vars    Done +
via env     suggest wiring
skill
创建数据库之前,务必先检查是否已存在数据库。
用户提及数据库
  先检查现有数据库
  (查询环境配置中的source.image)
   ┌────┴────┐
 已存在    不存在
    │           │
    │      创建数据库
    │      (CLI或API)
    │           │
    │      等待部署完成
    │           │
    └─────┬─────┘
    用户是否想要
    连接服务?
    ┌─────┴─────┐
   是         否
    │           │
通过env
Skill配置变量    完成 +
          建议配置连接

Check for Existing Databases

检查现有数据库

Before creating a database, check if one already exists.
For full environment config structure, see environment-config.md.
bash
railway status --json
Then query environment config and check
source.image
for each service:
graphql
query environmentConfig($environmentId: String!) {
  environment(id: $environmentId) {
    config(decryptVariables: false)
  }
}
The
config.services
object contains each service's configuration. Check
source.image
for:
  • ghcr.io/railway/postgres*
    or
    postgres:*
    → Postgres
  • ghcr.io/railway/redis*
    or
    redis:*
    → Redis
  • ghcr.io/railway/mysql*
    or
    mysql:*
    → MySQL
  • ghcr.io/railway/mongo*
    or
    mongo:*
    → MongoDB
创建数据库之前,请检查是否已存在对应的数据库。
完整的环境配置结构,请查看environment-config.md
bash
railway status --json
然后查询环境配置,检查每个服务的
source.image
graphql
query environmentConfig($environmentId: String!) {
  environment(id: $environmentId) {
    config(decryptVariables: false)
  }
}
config.services
对象包含每个服务的配置。检查
source.image
是否为以下值:
  • ghcr.io/railway/postgres*
    postgres:*
    → Postgres
  • ghcr.io/railway/redis*
    redis:*
    → Redis
  • ghcr.io/railway/mysql*
    mysql:*
    → MySQL
  • ghcr.io/railway/mongo*
    mongo:*
    → MongoDB

Available Databases

可用数据库

DatabaseTemplate Code
PostgreSQL
postgres
Redis
redis
MySQL
mysql
MongoDB
mongodb
数据库模板代码
PostgreSQL
postgres
Redis
redis
MySQL
mysql
MongoDB
mongodb

Prerequisites

前提条件

Get project context:
bash
railway status --json
Extract:
  • id
    - project ID
  • environments.edges[0].node.id
    - environment ID
Get workspace ID (not in status output):
bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'query getWorkspace($projectId: String!) {
    project(id: $projectId) { workspaceId }
  }' \
  '{"projectId": "PROJECT_ID"}'
SCRIPT
获取项目上下文:
bash
railway status --json
提取以下信息:
  • id
    - 项目ID
  • environments.edges[0].node.id
    - 环境ID
获取工作区ID(不在status输出中):
bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'query getWorkspace($projectId: String!) {
    project(id: $projectId) { workspaceId }
  }' \
  '{"projectId": "PROJECT_ID"}'
SCRIPT

Adding a Database

添加数据库

Step 1: Fetch Template

步骤1:获取模板

bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'query template($code: String!) {
    template(code: $code) {
      id
      name
      serializedConfig
    }
  }' \
  '{"code": "postgres"}'
SCRIPT
This returns the template's
id
and
serializedConfig
needed for deployment.
bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'query template($code: String!) {
    template(code: $code) {
      id
      name
      serializedConfig
    }
  }' \
  '{"code": "postgres"}'
SCRIPT
此命令会返回部署所需的模板
id
serializedConfig

Step 2: Deploy Template

步骤2:部署模板

bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'mutation deployTemplate($input: TemplateDeployV2Input!) {
    templateDeployV2(input: $input) {
      projectId
      workflowId
    }
  }' \
  '{
    "input": {
      "templateId": "TEMPLATE_ID",
      "serializedConfig": SERIALIZED_CONFIG,
      "projectId": "PROJECT_ID",
      "environmentId": "ENVIRONMENT_ID",
      "workspaceId": "WORKSPACE_ID"
    }
  }'
SCRIPT
Important:
serializedConfig
is the exact object from the template query, not a string.
bash
bash <<'SCRIPT'
scripts/railway-api.sh \
  'mutation deployTemplate($input: TemplateDeployV2Input!) {
    templateDeployV2(input: $input) {
      projectId
      workflowId
    }
  }' \
  '{
    "input": {
      "templateId": "TEMPLATE_ID",
      "serializedConfig": SERIALIZED_CONFIG,
      "projectId": "PROJECT_ID",
      "environmentId": "ENVIRONMENT_ID",
      "workspaceId": "WORKSPACE_ID"
    }
  }'
SCRIPT
重要提示
serializedConfig
是模板查询返回的完整对象,而非字符串。

Connecting to the Database

连接数据库

After deployment, other services connect using reference variables.
For complete variable reference syntax and wiring patterns, see variables.md.
部署完成后,其他服务可通过引用变量进行连接。
完整的变量引用语法和配置模式,请查看variables.md

Backend Services (Server-side)

后端服务(服务器端)

Use the private/internal URL for server-to-server communication:
DatabaseVariable Reference
PostgreSQL
${{Postgres.DATABASE_URL}}
Redis
${{Redis.REDIS_URL}}
MySQL
${{MySQL.MYSQL_URL}}
MongoDB
${{MongoDB.MONGO_URL}}
使用私有/内部URL进行服务器间通信:
数据库变量引用
PostgreSQL
${{Postgres.DATABASE_URL}}
Redis
${{Redis.REDIS_URL}}
MySQL
${{MySQL.MYSQL_URL}}
MongoDB
${{MongoDB.MONGO_URL}}

Frontend Applications

前端应用

Important: Frontends run in the user's browser and cannot access Railway's private network. They must use public URLs or go through a backend API.
For direct database access from frontend (not recommended):
  • Use the public URL variables (e.g.,
    ${{MongoDB.MONGO_PUBLIC_URL}}
    )
  • Requires TCP proxy to be enabled
Better pattern: Frontend → Backend API → Database
重要提示:前端在用户浏览器中运行,无法访问Railway的私有网络。必须使用公共URL或通过后端API进行访问。
如果要从前端直接访问数据库(不推荐):
  • 使用公共URL变量(例如
    ${{MongoDB.MONGO_PUBLIC_URL}}
  • 需要启用TCP代理
更好的模式:前端 → 后端API → 数据库

Example: Add PostgreSQL

示例:添加PostgreSQL

bash
bash <<'SCRIPT'
bash
bash <<'SCRIPT'

1. Get context

1. 获取上下文

railway status --json
railway status --json

Extract project.id and environment.id

提取project.id和environment.id

2. Get workspace ID

2. 获取工作区ID

scripts/railway-api.sh
'query { project(id: "proj-id") { workspaceId } }' '{}'
scripts/railway-api.sh
'query { project(id: "proj-id") { workspaceId } }' '{}'

3. Fetch Postgres template

3. 获取Postgres模板

scripts/railway-api.sh
'query { template(code: "postgres") { id serializedConfig } }' '{}'
scripts/railway-api.sh
'query { template(code: "postgres") { id serializedConfig } }' '{}'

4. Deploy template

4. 部署模板

scripts/railway-api.sh
'mutation deploy($input: TemplateDeployV2Input!) { templateDeployV2(input: $input) { projectId workflowId } }'
'{"input": {"templateId": "...", "serializedConfig": {...}, "projectId": "...", "environmentId": "...", "workspaceId": "..."}}' SCRIPT
undefined
scripts/railway-api.sh
'mutation deploy($input: TemplateDeployV2Input!) { templateDeployV2(input: $input) { projectId workflowId } }'
'{"input": {"templateId": "...", "serializedConfig": {...}, "projectId": "...", "environmentId": "...", "workspaceId": "..."}}' SCRIPT
undefined

Then Connect From Another Service

然后连接到其他服务

Use
environment
skill to add the variable reference:
json
{
  "services": {
    "<backend-service-id>": {
      "variables": {
        "DATABASE_URL": { "value": "${{Postgres.DATABASE_URL}}" }
      }
    }
  }
}
使用
environment
Skill添加变量引用:
json
{
  "services": {
    "<backend-service-id>": {
      "variables": {
        "DATABASE_URL": { "value": "${{Postgres.DATABASE_URL}}" }
      }
    }
  }
}

Response

响应

Successful deployment returns:
json
{
  "data": {
    "templateDeployV2": {
      "projectId": "e63baedb-e308-49e9-8c06-c25336f861c7",
      "workflowId": "deployTemplate/project/e63baedb-e308-49e9-8c06-c25336f861c7/xxx"
    }
  }
}
部署成功后会返回:
json
{
  "data": {
    "templateDeployV2": {
      "projectId": "e63baedb-e308-49e9-8c06-c25336f861c7",
      "workflowId": "deployTemplate/project/e63baedb-e308-49e9-8c06-c25336f861c7/xxx"
    }
  }
}

What Gets Created

创建的资源

Each database template creates:
  • A service with the database image
  • A volume for data persistence
  • Environment variables for connection strings
  • TCP proxy for external access (where applicable)
每个数据库模板会创建:
  • 一个带有数据库镜像的服务
  • 用于数据持久化的存储卷
  • 用于连接字符串的环境变量
  • 用于外部访问的TCP代理(如适用)

Error Handling

错误处理

ErrorCauseSolution
Template not foundInvalid template codeUse:
postgres
,
redis
,
mysql
,
mongodb
Permission deniedUser lacks accessNeed DEVELOPER role or higher
Project not foundInvalid project IDRun
railway status --json
for correct ID
错误原因解决方案
模板未找到无效的模板代码使用:
postgres
redis
mysql
mongodb
权限被拒绝用户权限不足需要DEVELOPER或更高角色
项目未找到无效的项目ID运行
railway status --json
获取正确的ID

Example Workflows

示例工作流

"add postgres and connect to the server"

"add postgres and connect to the server"

  1. Check existing DBs via env config query
  2. If postgres exists: Skip to step 5
  3. If not exists: Deploy postgres template (fetch template → deploy)
  4. Wait for deployment to complete
  5. Identify target service (ask if multiple, or use linked service)
  6. Use
    environment
    skill to stage:
    DATABASE_URL: { "value": "${{Postgres.DATABASE_URL}}" }
  7. Apply changes
  1. 通过环境配置查询检查现有数据库
  2. 如果Postgres已存在:跳至步骤5
  3. 如果不存在:部署Postgres模板(获取模板 → 部署)
  4. 等待部署完成
  5. 确定目标服务(如果有多个则询问用户,或使用关联服务)
  6. 使用
    environment
    Skill配置:
    DATABASE_URL: { "value": "${{Postgres.DATABASE_URL}}" }
  7. 应用更改

"add postgres"

"add postgres"

  1. Check existing DBs via env config query
  2. If exists: "Postgres already exists in this project"
  3. If not exists: Deploy postgres template
  4. Inform user: "Postgres created. Connect a service with:
    DATABASE_URL=${{Postgres.DATABASE_URL}}
    "
  1. 通过环境配置查询检查现有数据库
  2. 如果已存在:“此项目中已存在Postgres”
  3. 如果不存在:部署Postgres模板
  4. 通知用户:“Postgres已创建。使用以下命令连接服务:
    DATABASE_URL=${{Postgres.DATABASE_URL}}

"connect the server to redis"

"connect the server to redis"

  1. Check existing DBs via env config query
  2. If redis exists: Wire up REDIS_URL via environment skill → apply
  3. If no redis: Ask "No Redis found. Create one?"
    • Deploy redis template
    • Wire REDIS_URL → apply
  1. 通过环境配置查询检查现有数据库
  2. 如果Redis已存在:通过environment Skill配置REDIS_URL → 应用更改
  3. 如果不存在Redis:询问用户“未找到Redis。是否创建一个?”
    • 部署Redis模板
    • 配置REDIS_URL → 应用更改

Composability

可组合性

  • Connect services: Use
    environment
    skill to add variable references
  • View database service: Use
    service
    skill
  • Check logs: Use
    deployment
    skill
  • 连接服务:使用
    environment
    Skill添加变量引用
  • 查看数据库服务:使用
    service
    Skill
  • 查看日志:使用
    deployment
    Skill