Deploy Mastra to Amazon EC2
Deploy your Mastra server to Amazon EC2. This gives you full control over your server environment and supports long-running agents and workflows.
This guide covers deploying the Mastra server. If you're using a server adapter or web framework, deploy the way you normally would for that framework.
Before you beginDirect link to Before you begin
You'll need:
- A Mastra application
- An EC2 instance (Ubuntu or Amazon Linux) with Git and Node.js 22.13.0+ installed
For production, you'll also need:
- A domain name pointing to your instance (required for SSL certificates)
- An SSL certificate for your domain (e.g., using Certbot with Let's Encrypt)
- A reverse proxy (e.g., nginx) to forward traffic to your application
DeployDirect link to Deploy
Connect to your EC2 instance and clone your repository:
- Public Repository
- Private Repository
git clone https://github.com/<your-username>/<your-repository>.gitgit clone git@github.com:<your-username>/<your-repository>.gitNavigate to the repository directory:
cd "<your-repository>"Install dependencies:
- npm
- pnpm
- Yarn
- Bun
npm installpnpm installyarn installbun installCreate a
.envfile and add your environment variables:touch .envRemember to set your environment variables needed to run your application (e.g. your model provider API key):
OPENAI_API_KEY=<your-openai-api-key>
# Add other required environment variablesBuild the application:
- npm
- pnpm
- Yarn
- Bun
npm run buildpnpm run buildyarn buildbun run buildRun the application:
node --env-file=".env" .mastra/output/index.mjsThis is a basic example. In production, use a process manager like PM2 or systemd to keep your application running and handle restarts.
warningSet up authentication before exposing your endpoints publicly.
Your Mastra server is now running on port 4111, but it's only accessible locally.
You can open port 4111 in your EC2 security group for direct access, or configure a reverse proxy (such as nginx) to listen on ports 80 and 443 and forward requests to
http://localhost:4111.In production, you should use a reverse proxy so you can configure HTTPS. HTTPS encrypts traffic and is required for most webhook integrations and external services your agents interact with.
Verify your deployment at
https://<your-ec2-address>/api/agents, which should return a JSON list of your agents.You can now call your Mastra endpoints over HTTP.