database
This skill should be used when the user wants to add a database (Postgres, Redis, MySQL, MongoDB), says "add postgres", "add redis", "add database", "connect to database", or "wire up the database". For other templates (Ghost, Strapi, n8n, etc.), use the templates skill.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install railwayapp-railway-skills-database
Repository
Skill path: plugins/railway/skills/database
This skill should be used when the user wants to add a database (Postgres, Redis, MySQL, MongoDB), says "add postgres", "add redis", "add database", "connect to database", or "wire up the database". For other templates (Ghost, Strapi, n8n, etc.), use the templates skill.
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Backend.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: railwayapp.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install database into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/railwayapp/railway-skills before adding database to shared team environments
- Use database for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: database
description: This skill should be used when the user wants to add a database (Postgres, Redis, MySQL, MongoDB), says "add postgres", "add redis", "add database", "connect to database", or "wire up the database". For other templates (Ghost, Strapi, n8n, etc.), use the templates skill.
allowed-tools: Bash(railway:*)
---
# 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.
## 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"
## 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
```
## Check for Existing Databases
Before creating a database, check if one already exists.
For full environment config structure, see [environment-config.md](references/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
## Available Databases
| Database | Template Code |
|----------|---------------|
| 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
```
## Adding a Database
### Step 1: Fetch Template
```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.
### Step 2: Deploy Template
```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.
## Connecting to the Database
After deployment, other services connect using reference variables.
For complete variable reference syntax and wiring patterns, see [variables.md](references/variables.md).
### Backend Services (Server-side)
Use the private/internal URL for server-to-server communication:
| Database | Variable Reference |
|----------|-------------------|
| 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
## Example: Add PostgreSQL
```bash
bash <<'SCRIPT'
# 1. Get context
railway status --json
# Extract project.id and environment.id
# 2. Get workspace ID
scripts/railway-api.sh \
'query { project(id: "proj-id") { workspaceId } }' '{}'
# 3. Fetch Postgres template
scripts/railway-api.sh \
'query { template(code: "postgres") { id serializedConfig } }' '{}'
# 4. Deploy template
scripts/railway-api.sh \
'mutation deploy($input: TemplateDeployV2Input!) {
templateDeployV2(input: $input) { projectId workflowId }
}' \
'{"input": {"templateId": "...", "serializedConfig": {...}, "projectId": "...", "environmentId": "...", "workspaceId": "..."}}'
SCRIPT
```
### 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}}" }
}
}
}
}
```
## Response
Successful deployment returns:
```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)
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Template not found | Invalid template code | Use: `postgres`, `redis`, `mysql`, `mongodb` |
| Permission denied | User lacks access | Need DEVELOPER role or higher |
| Project not found | Invalid project ID | Run `railway status --json` for correct ID |
## Example Workflows
### "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
### "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}}`"
### "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
## Composability
- **Connect services**: Use `environment` skill to add variable references
- **View database service**: Use `service` skill
- **Check logs**: Use `deployment` skill
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### references/environment-config.md
```markdown
# Environment Config Reference
The `EnvironmentConfig` object is used to configure services, volumes, and shared variables in Railway.
## Structure
```json
{
"services": {
"<serviceId>": {
"source": { ... },
"build": { ... },
"deploy": { ... },
"variables": { ... },
"networking": { ... }
}
},
"sharedVariables": { ... },
"volumes": { ... },
"buckets": { ... }
}
```
Only include fields being changed. The patch is merged with existing config.
## Service Config
### Source
| Field | Type | Description |
|-------|------|-------------|
| `image` | string | Docker image (e.g., `nginx:latest`) |
| `repo` | string | Git repository URL |
| `branch` | string | Git branch to deploy |
| `commitSha` | string | Specific commit SHA |
| `rootDirectory` | string | Root directory (monorepos) |
| `checkSuites` | boolean | Wait for GitHub check suites |
| `autoUpdates.type` | disabled \| patch \| minor | Auto-update policy for Docker images |
### Build
| Field | Type | Description |
|-------|------|-------------|
| `builder` | NIXPACKS \| DOCKERFILE \| RAILPACK | Build system |
| `buildCommand` | string | Command for Nixpacks builds |
| `dockerfilePath` | string | Path to Dockerfile |
| `watchPatterns` | string[] | Patterns to trigger deploys |
| `nixpacksConfigPath` | string | Path to nixpacks config |
### Deploy
| Field | Type | Description |
|-------|------|-------------|
| `startCommand` | string | Container start command |
| `multiRegionConfig` | object | Region → replica config. See [Multi-Region Config](#multi-region-config). |
| `healthcheckPath` | string | Health check endpoint |
| `healthcheckTimeout` | number | Seconds to wait for health |
| `restartPolicyType` | ON_FAILURE \| ALWAYS \| NEVER | Restart behavior |
| `restartPolicyMaxRetries` | number | Max restart attempts |
| `cronSchedule` | string | Cron schedule for cron jobs |
| `sleepApplication` | boolean | Sleep when inactive |
### Variables
| Field | Type | Description |
|-------|------|-------------|
| `value` | string | Variable value |
| `isOptional` | boolean | Allow empty value |
Set to `null` to delete a variable.
For variable references, see [variables.md](variables.md).
### Lifecycle
| Field | Type | Description |
|-------|------|-------------|
| `isDeleted` | boolean | Mark for deletion (requires ADMIN) |
| `isCreated` | boolean | Mark as newly created |
## Multi-Region Config
Controls replica count per region. Structure: region name → `{ numReplicas }` or `null` to remove.
```json
{
"multiRegionConfig": {
"us-west2": { "numReplicas": 3 },
"europe-west4-drams3a": { "numReplicas": 2 }
}
}
```
### Available Regions
| Name | Location | Aliases |
|------|----------|---------|
| `us-west2` | US West (California) | "us west", "california" |
| `us-east4-eqdc4a` | US East (Virginia) | "us east", "virginia" |
| `europe-west4-drams3a` | EU West (Amsterdam) | "europe", "eu", "amsterdam" |
| `asia-southeast1-eqsg3a` | Southeast Asia (Singapore) | "asia", "singapore" |
### Interpreting User Requests
- "add 3 replicas to europe" → `{ "europe-west4-drams3a": { "numReplicas": 3 } }`
- "add a replica to all regions" → set `numReplicas: 1` for all 4 regions
- "remove from asia" → `{ "asia-southeast1-eqsg3a": null }`
- "increase replicas to 5" (no region specified) → query current config first, update existing region(s)
**Important:** When user doesn't specify a region, query the current `multiRegionConfig` and modify the existing region(s). Don't assume a default region.
## Common Operations
### Set Build Command
```json
{ "services": { "<serviceId>": { "build": { "buildCommand": "npm run build" } } } }
```
### Set Start Command
```json
{ "services": { "<serviceId>": { "deploy": { "startCommand": "node server.js" } } } }
```
### Set Replicas
```json
{ "services": { "<serviceId>": { "deploy": { "multiRegionConfig": { "us-west2": { "numReplicas": 3 } } } } } }
```
### Add Variables
```json
{ "services": { "<serviceId>": { "variables": { "API_KEY": { "value": "xxx" } } } } }
```
### Delete Variable
```json
{ "services": { "<serviceId>": { "variables": { "OLD_VAR": null } } } }
```
### Add Shared Variable
```json
{ "sharedVariables": { "DATABASE_URL": { "value": "postgres://..." } } }
```
### Change Docker Image
```json
{ "services": { "<serviceId>": { "source": { "image": "nginx:latest" } } } }
```
### Connect GitHub Repo
```json
{ "services": { "<serviceId>": { "source": { "repo": "owner/repo", "branch": "main" } } } }
```
### Change Git Branch
```json
{ "services": { "<serviceId>": { "source": { "branch": "develop" } } } }
```
### Set Health Check
```json
{ "services": { "<serviceId>": { "deploy": { "healthcheckPath": "/health", "healthcheckTimeout": 30 } } } }
```
### Change Builder
```json
{ "services": { "<serviceId>": { "build": { "builder": "DOCKERFILE", "dockerfilePath": "./Dockerfile" } } } }
```
### Delete Service
```json
{ "services": { "<serviceId>": { "isDeleted": true } } }
```
### Delete Volume
```json
{ "volumes": { "<volumeId>": { "isDeleted": true } } }
```
### New Service Instance
```json
{ "services": { "<serviceId>": { "isCreated": true, "source": { "image": "nginx" } } } }
```
**Note:** `isCreated: true` is required for new service instances.
```
### references/variables.md
```markdown
# Variables Reference
Variables in Railway support references to other services, shared variables, and Railway-provided values.
## Template Syntax
```
${{NAMESPACE.VAR}}
```
| Namespace | Description |
|-----------|-------------|
| `shared` | Shared variables (project-wide) |
| `<serviceName>` | Variables from another service (case-sensitive) |
## Examples
**Reference shared variable:**
```json
{ "value": "${{shared.DOMAIN}}" }
```
**Reference another service's variable:**
```json
{ "value": "${{api.API_KEY}}" }
```
**Combine with text:**
```json
{ "value": "https://${{shared.DOMAIN}}/api" }
```
## Railway-Provided Variables
Railway injects these into every service automatically.
### Networking
| Variable | Description | Example | Availability |
|----------|-------------|---------|--------------|
| `RAILWAY_PUBLIC_DOMAIN` | Public domain | `myapp.up.railway.app` | Only if service has a domain |
| `RAILWAY_PRIVATE_DOMAIN` | Private DNS (internal only) | `myapp.railway.internal` | Always |
| `RAILWAY_TCP_PROXY_DOMAIN` | TCP proxy domain | `roundhouse.proxy.rlwy.net` | Only if TCP proxy enabled |
| `RAILWAY_TCP_PROXY_PORT` | TCP proxy port | `11105` | Only if TCP proxy enabled |
**Note:** `RAILWAY_PUBLIC_DOMAIN` is only available if the service has a domain configured.
Check the service's environment config to verify a domain exists before referencing it.
### Context
| Variable | Description |
|----------|-------------|
| `RAILWAY_PROJECT_ID` | Project ID |
| `RAILWAY_PROJECT_NAME` | Project name |
| `RAILWAY_ENVIRONMENT_ID` | Environment ID |
| `RAILWAY_ENVIRONMENT_NAME` | Environment name |
| `RAILWAY_SERVICE_ID` | Service ID |
| `RAILWAY_SERVICE_NAME` | Service name |
| `RAILWAY_DEPLOYMENT_ID` | Deployment ID |
| `RAILWAY_REPLICA_ID` | Replica ID |
| `RAILWAY_REPLICA_REGION` | Region (e.g., `us-west2`) |
### Volume (if attached)
| Variable | Description |
|----------|-------------|
| `RAILWAY_VOLUME_NAME` | Volume name |
| `RAILWAY_VOLUME_MOUNT_PATH` | Mount path |
### Git (if deployed from GitHub)
| Variable | Description |
|----------|-------------|
| `RAILWAY_GIT_COMMIT_SHA` | Commit SHA |
| `RAILWAY_GIT_BRANCH` | Branch name |
| `RAILWAY_GIT_REPO_NAME` | Repository name |
| `RAILWAY_GIT_REPO_OWNER` | Repository owner |
| `RAILWAY_GIT_AUTHOR` | Commit author |
| `RAILWAY_GIT_COMMIT_MESSAGE` | Commit message |
## Wiring Services Together
### Frontend → Backend (public network)
Use when: Browser makes requests to API (browser can't access private network)
```json
{
"services": {
"<frontendId>": {
"variables": {
"API_URL": { "value": "https://${{backend.RAILWAY_PUBLIC_DOMAIN}}" }
}
}
}
}
```
### Service → Database (private network)
Use when: Backend connects to database (faster, no egress cost, more secure)
Railway databases auto-generate connection URL variables. Use the private versions:
| Database | Variable Reference |
|----------|-------------------|
| Postgres | `${{Postgres.DATABASE_URL}}` |
| MySQL | `${{MySQL.DATABASE_URL}}` |
| Redis | `${{Redis.REDIS_URL}}` |
| Mongo | `${{Mongo.MONGO_URL}}` |
**Postgres/MySQL example:**
```json
{
"services": {
"<apiId>": {
"variables": {
"DATABASE_URL": { "value": "${{Postgres.DATABASE_URL}}" }
}
}
}
}
```
**Redis example:**
```json
{
"services": {
"<apiId>": {
"variables": {
"REDIS_URL": { "value": "${{Redis.REDIS_URL}}" }
}
}
}
}
```
**Mongo example:**
```json
{
"services": {
"<apiId>": {
"variables": {
"MONGO_URL": { "value": "${{Mongo.MONGO_URL}}" }
}
}
}
}
```
**Note:** Service names are case-sensitive. Match the exact name from your project (e.g., "Postgres", "Redis").
### Service → Service (private network)
Use when: Microservices communicate internally
```json
{
"services": {
"<workerServiceId>": {
"variables": {
"API_INTERNAL_URL": { "value": "http://${{api.RAILWAY_PRIVATE_DOMAIN}}:${{api.PORT}}" }
}
}
}
}
```
## When to Use Public vs Private
| Use Case | Domain | Reason |
|----------|--------|--------|
| Browser → API | Public | Browser can't access private network |
| Service → Service | Private | Faster, no egress, more secure |
| Service → Database | Private | Databases should never be public |
| External webhook → Service | Public | External services need public access |
| Cron job → API | Private | Internal communication |
```
### scripts/railway-api.sh
```bash
#!/usr/bin/env bash
# Railway GraphQL API helper
# Usage: railway-api.sh '<graphql-query>' ['<variables-json>']
set -e
if ! command -v jq &>/dev/null; then
echo '{"error": "jq not installed. Install with: brew install jq"}'
exit 1
fi
CONFIG_FILE="$HOME/.railway/config.json"
if [[ ! -f "$CONFIG_FILE" ]]; then
echo '{"error": "Railway config not found. Run: railway login"}'
exit 1
fi
TOKEN=$(jq -r '.user.token' "$CONFIG_FILE")
if [[ -z "$TOKEN" || "$TOKEN" == "null" ]]; then
echo '{"error": "No Railway token found. Run: railway login"}'
exit 1
fi
if [[ -z "$1" ]]; then
echo '{"error": "No query provided"}'
exit 1
fi
# Build payload with query and optional variables
if [[ -n "$2" ]]; then
PAYLOAD=$(jq -n --arg q "$1" --argjson v "$2" '{query: $q, variables: $v}')
else
PAYLOAD=$(jq -n --arg q "$1" '{query: $q}')
fi
curl -s https://backboard.railway.com/graphql/v2 \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "$PAYLOAD"
```