---
title: "Deploy Mastra"
description: "A TypeScript AI agent platform with Studio, workflows & persistent memory."
category: "AI/ML"
url: https://railway.com/deploy/mastra
---

# Deploy Mastra

A TypeScript AI agent platform with Studio, workflows & persistent memory.

**[Deploy Mastra on Railway](https://railway.com/template/mastra)**

Machine-readable deploy manifest (JSON, validated by TemplateCI): https://railway.com/deploy/mastra/manifest.json

- **Creator:** INF Labs
- **Category:** AI/ML

## Template content

### Mastra https://mastra.ai/brand/assets/logo/mastra-logo-white.svg

- **Source:** codestorm-official/mastra
- **Public domain:** Yes

### Postgres https://devicons.railway.app/i/postgresql.svg

- **Image:** ghcr.io/railwayapp-templates/postgres-ssl:18

## Documentation

# Deploy and Host Mastra on Railway

Mastra is a TypeScript framework for building AI agents, workflows, tools, and production-ready AI applications.

This Railway template deploys **Mastra with PostgreSQL**, providing a production Mastra server with Studio, persistent storage, agent memory, workflows, health monitoring, and multi-provider AI model support.

## About Hosting Mastra

Mastra provides a complete TypeScript-native framework for building and operating AI-powered applications.

This template runs Mastra as a standalone production server and includes **Mastra Studio** in the production build, allowing you to inspect and interact with registered agents, workflows, and tools directly from your browser.

PostgreSQL is used as the persistent storage backend through Mastra's official PostgreSQL integration, allowing application state to survive container restarts and Railway redeployments.

The Mastra application is publicly accessible, while PostgreSQL remains available only through Railway private networking.

## Common Use Cases

* Build AI agents with TypeScript
* Create multi-step AI workflows
* Develop AI assistants
* Build agent-powered APIs
* Persist agent memory and conversation state
* Create human-in-the-loop workflows
* Develop AI automation pipelines
* Experiment with multiple LLM providers
* Build internal AI tools
* Develop MCP-compatible AI applications
* Inspect agents and workflows using Mastra Studio
* Build production AI backends

## Dependencies for Mastra Hosting

This template includes:

* **Mastra** — AI agent and workflow runtime
* **Mastra Studio** — Browser-based development and inspection interface
* **PostgreSQL** — Persistent application storage
* **Railway Private Networking** — Internal database communication

## Mastra Studio

This template builds Mastra using:

```text
mastra build --studio
```

Mastra's production build can include the Studio interface inside the generated `.mastra/output` deployment artifact.

After deployment:

1. Generate a Railway public domain for the Mastra service.
2. Open the assigned Mastra public URL.
3. Use Mastra Studio to inspect and interact with the registered application components.

The included starter application registers:

* Assistant agent
* Example workflow
* PostgreSQL storage

No separate frontend service is required.

## Persistent PostgreSQL Storage

This template uses Mastra's official PostgreSQL storage package:

```text
@mastra/pg
```

The application connects to PostgreSQL using:

```text
DATABASE_URL
```

On Railway, the Mastra service references the PostgreSQL service through:

```text
${{Postgres.DATABASE_URL}}
```

The template uses PostgreSQL for persistent Mastra state, allowing application data to survive:

* Mastra restarts
* Container replacements
* Railway redeployments
* Application upgrades

The Mastra application itself does not require a Railway Volume.

## Supported AI Providers

The starter agent supports:

| Provider  | Environment Variable           | Example Model                   |
| --------- | ------------------------------ | ------------------------------- |
| OpenAI    | `OPENAI_API_KEY`               | `gpt-4o-mini`                   |
| Anthropic | `ANTHROPIC_API_KEY`            | Provider-supported Claude model |
| Google    | `GOOGLE_GENERATIVE_AI_API_KEY` | Provider-supported Gemini model |

Select the provider using:

```text
MODEL_PROVIDER
```

Supported values:

```text
openai
anthropic
google
```

Configure the model using:

```text
MODEL_NAME
```

The repository generates the model identifier from the selected provider and model configuration.

## Important Environment Variables

### `DATABASE_URL`

Required PostgreSQL connection URL used by Mastra for persistent storage.

Railway automatically references the included PostgreSQL service.

### `MODEL_PROVIDER`

Defines the active model provider.

Supported values:

* `openai`
* `anthropic`
* `google`

Default:

```text
openai
```

### `MODEL_NAME`

Defines the provider-specific model name.

Default:

```text
gpt-4o-mini
```

### Provider API Keys

Configure only the credential required by the selected provider:

* `OPENAI_API_KEY`
* `ANTHROPIC_API_KEY`
* `GOOGLE_GENERATIVE_AI_API_KEY`

An AI provider API key is required when invoking the corresponding agent, but the Mastra service itself can be configured independently of unrelated provider credentials.

### `SYSTEM_PROMPT`

Optional default instructions used by the starter assistant agent.

### `PORT`

HTTP port used by the Mastra production server.

Default:

```text
4111
```

### `NODE_ENV`

Set to:

```text
production
```

for Railway deployment.

## Starter Agent

The template includes a starter agent named:

```text
assistant
```

The agent uses:

* Configurable AI provider
* Configurable model
* Configurable system prompt
* PostgreSQL-backed Mastra storage

It provides a starting point for creating custom AI assistants and agent-powered applications.

## Starter Workflow

An example workflow is included so the deployment immediately contains a functional Mastra workflow.

The workflow can be inspected and executed through Mastra Studio and serves as a reference for building:

* Sequential AI processes
* Multi-step transformations
* Agent-driven workflows
* Human-in-the-loop processes
* Automated AI pipelines

## Health Endpoint

The template exposes:

```text
GET /health
```

The health route verifies both:

* Mastra application availability
* PostgreSQL connectivity

Healthy response:

```json
{
  "status": "ok",
  "database": "ok"
}
```

If PostgreSQL is unavailable, the endpoint returns HTTP `503`.

The health check does not invoke an AI provider.

## Railway Deployment

The template deploys two services:

```text
Internet
   │
   ▼
Railway HTTPS
   │
   ▼
Mastra
:4111
   │
   │ Railway Private Network
   ▼
PostgreSQL
:5432
```

### Mastra Service

Recommended configuration:

* Source: GitHub repository
* Public Domain: enabled
* Port: `4111`
* Health Check: `/health`
* Volume: not required
* Custom Start Command: not required
* `RAILWAY_RUN_UID`: not required

The production image starts the generated Mastra server directly from:

```text
.mastra/output/index.mjs
```

The Dockerfile runs the application as a non-root Node.js user.

### PostgreSQL Service

Recommended configuration:

* Public Domain: disabled
* Private Networking: enabled
* Port: `5432`
* Persistent Volume: enabled

PostgreSQL should remain private and should not be exposed directly to the internet.

## After Deployment

1. Wait for PostgreSQL to become available.
2. Wait for the Mastra service to become healthy.
3. Generate a public domain for Mastra on port `4111`.
4. Set `MODEL_PROVIDER`.
5. Set `MODEL_NAME`.
6. Add the API key for the selected AI provider.
7. Open the Mastra public URL.
8. Access Mastra Studio.
9. Inspect the included `assistant` agent.
10. Run the included example workflow.
11. Verify `/health` returns a successful database status.

## Persistent Storage Model

The deployment uses:

```text
Mastra
   │
   ▼
PostgreSQL
   │
   ▼
Railway Volume
```

Mastra itself remains stateless from the container filesystem perspective.

This means:

* No Mastra application volume is required
* Redeployments do not remove PostgreSQL-backed state
* Application containers can be replaced safely
* PostgreSQL remains the persistent data layer

## Security Notes

For production deployments:

* Keep PostgreSQL private
* Never expose `DATABASE_URL`
* Never commit AI provider API keys
* Use scoped provider credentials where possible
* Rotate exposed credentials immediately
* Review Studio exposure before using the template for sensitive workloads
* Avoid exposing administrative development interfaces unnecessarily
* Review authentication requirements before deploying sensitive or multi-user applications

This starter focuses on simple self-hosted deployment and does not add custom authentication that is not part of the configured Mastra application.

## Mastra vs Alternatives

| Feature                   | Mastra | Pydantic AI | Agno |        CrewAI |
| ------------------------- | -----: | ----------: | ---: | ------------: |
| TypeScript-native         |      ✅ |           ❌ |    ❌ |             ❌ |
| Agent framework           |      ✅ |           ✅ |    ✅ |             ✅ |
| Workflow engine           |      ✅ |          ⚠️ |    ✅ |             ✅ |
| Studio / visual interface |      ✅ |          ⚠️ |    ✅ |            ⚠️ |
| PostgreSQL storage        |      ✅ |           ✅ |    ✅ | App-dependent |
| Persistent memory         |      ✅ |           ✅ |    ✅ |             ✅ |
| Multi-provider models     |      ✅ |           ✅ |    ✅ |             ✅ |
| Human-in-the-loop         |      ✅ |           ✅ |    ✅ |             ✅ |
| MCP support               |      ✅ |           ✅ |    ✅ |             ✅ |
| Observability             |      ✅ |           ✅ |    ✅ |            ⚠️ |
| Self-hosted runtime       |      ✅ |           ✅ |    ✅ |             ✅ |

Mastra is particularly well suited for developers who want an AI agent and workflow platform built around the TypeScript ecosystem.

## Why Deploy Mastra on Railway?

Railway provides a simple environment for running Mastra together with its persistent PostgreSQL backend.

Deploying Mastra on Railway provides:

* Automatic HTTPS domains
* Railway private networking
* Persistent PostgreSQL storage
* Built-in environment variable management
* Simple secret configuration
* Integrated deployment logs
* Easy application redeployments
* Mastra Studio in the production build
* No application volume requirement
* No Redis dependency for the standard deployment
* A clean two-service architecture

This template provides a practical starting point for building and operating **TypeScript-based AI agents, workflows, and AI applications with Mastra and PostgreSQL**.


## Similar templates

- [Chat Chat](https://railway.com/deploy/-WWW5r) — Chat Chat, your own unified chat and search to AI platform.
- [stella](https://railway.com/deploy/stella) — Self-host stella with web, API, Postgres, Redis, and object storage.
- [Hermes Agent | OpenClaw Alternative with Dashboard](https://railway.com/deploy/hermes-agent-or-openclaw-alternative-wit) — Self-Hosted Hermes AI Agent for Telegram, Discord & Slack

Open this page in a browser: https://railway.com/deploy/mastra
