惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
罗磊的独立博客
博客园 - 聂微东
T
Troy Hunt's Blog
美团技术团队
IT之家
IT之家
A
Arctic Wolf
腾讯CDC
雷峰网
雷峰网
SecWiki News
SecWiki News
博客园_首页
L
LINUX DO - 最新话题
Cloudbric
Cloudbric
量子位
N
News and Events Feed by Topic
小众软件
小众软件
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cyberwarzone
Cyberwarzone
J
Java Code Geeks
V
V2EX
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Latest news
Latest news
Webroot Blog
Webroot Blog
F
Fortinet All Blogs
P
Privacy International News Feed
NISL@THU
NISL@THU
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
PCI Perspectives
PCI Perspectives
GbyAI
GbyAI
宝玉的分享
宝玉的分享
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
V
Visual Studio Blog

Railway Blog

Where Railway is, and where it's going (Summer 2026) PaaS vs IaaS vs SaaS: What Each Means and Who Should Pick What in 2026 The Best Continuous Deployment Tools in 2026 The Best PaaS for Multi-Region Deployments in 2026 The Best Platforms for Monorepo Deployments in 2026 Compliance Isn't a Feature, It's a Posture What is BYOC (Bring Your Own Cloud)? A Developer's Guide for 2026 The Best Managed Kubernetes Hosting in 2026 The Best Container Registries in 2026 The Vanilla Cloud Tax: What Rolling Your Own on AWS Actually Costs What is a PaaS? A Developer's Guide for 2026 The Best Cloud Observability and Logging Tools in 2026 The Best PostgreSQL Hosting for Developers in 2026 The Best Multi-Region Hosting Platforms in 2026 The Best Platforms to Deploy AI Apps in 2026 (Not the Models, the Apps Around Them) The Agent-Native Cloud: What It Means and Why It Matters Incident Report: May 19, 2026- GCP Account Suspension Counting to 3 with a new builder processing 50M+ monthly builds Railway iOS preview now available via TestFlight Kill your onboarding: selling to 10,000+ new users a day Your AI wants to nuke your database. Guardrails fix that. Better Rails for Agents: A New Remote MCP and Railway Agent in the CLI Moving Railway's Frontend Off Next.js One command deploys, there's a Stripe APP for that From registrar to deployed: buying a domain inside Railway A letter to open source builders who deserve more Networking is a black box, we used eBPF to open it Heroku Walked So Railway Can Run Security Features Your Security Team Will Love Railway Runs Open Source, Now We're Funding It Railway raises $100M Series B to unburden the builders Deploy autoscaling services, AI Workflow automation, and LLM APIs Without Kubernetes Hosting Postgres with GeoLite2: a practical guide to IP geolocation, data loading, and updates Serverless functions vs containers: CI/CD, database connections, cron jobs, and long-running tasks Hosting Postgres with pgvector: provider tradeoffs, migrations, indexes, and tuning Introducing the Railway integration on Delve.co Secure Cloud Hosting for Compliance: A Practical Guide for Startups and Regulated Industries How G2X Unlocked Rapid Experimentation at Scale with Railway MindFort Runs 100+ AI Pen Testing Agents Without Their Previous $10k AWS Bill How Bilt's Marketing Engineering Team Delivers at Scale with Railway Railway Technology Partners: Earn Revenue on Templates You Didn't Build ~$1 Million Paid to Developers Who Built Railway Templates CI/CD for Modern Deployment: From Manual Deploys to PR Environments Kernel Powers 1,000+ AI Agents on $444/Month of Railway Infrastructure Deploy Full-Stack TypeScript Apps: Architectures, Execution Models, and Deployment Choices Railway vs Cloudflare: How Their Architectures Differ and When to Use Each Run Scheduled and Recurring Tasks with Cron Monitoring & Observability: Using Logs, Metrics, Traces, and Alerts to Understand System Failures Logs, Metrics, and Traces: What Does Each Signal Tell You? Server rendering benchmarks: Railway vs Cloudflare vs Vercel Top five Heroku alternatives Comparing top PaaS and deployment providers Pricing to Encourage Use The F in SOC2 stands for functional Deploy Together, Earn Together: Introducing Railway Partnerships How We Oops-Proofed Infrastructure Deletion on Railway Bring Back the Free Plan Railway MCP - Stateful, Serverful, Pay-per-use Infrastructure Hackathon: Winners Announced! Mark Your Calendar: Railway User Hackathon with Prizes Launching Railway's Affiliate Program Zero-Touch Bare Metal at Scale Ssh, We’re Announcing One More Thing! $1M for Open Source Introducing Central Station Speed Isn’t Just About Code, It’s About Where That Code Runs One-Second Deploys? We Didn’t Believe It Either Why We’re Moving on From Nix Railway V3: Faster and Cheaper How to Migrate from Cloudflare Pages to Railway Supercharging Directus on Railway with a Static Frontend How to Migrate from AWS Lambda to Railway Deploy Triton Inference Server on Railway How to Handle Database Connection Pooling Manually Optimize Deployments on Railway Implement a GitHub Actions Testing Suite Scaling a SaaS application on Railway Building a SaaS application on Railway Deploy a Dart App on Railway, Part 2 Deploy a Dart App on Railway, Part 1 Implementing Feature Flags from Scratch Cron Jobs with Django and GitHub Actions Deploy Offen on Railway Queues on Railway Working with NX, Railway and CI/CD Automated PostgreSQL Backups Using GitLab CI/CD with Railway Migrating From Heroku To Railway Cron Jobs on Railway Deploy Beam on Railway Deploy Authorizer on Railway Deploying Monorepo Applications How to Backup and Restore Your Postgres Database How to Backup Your Redis Instance Deploy Cusdis on Railway Deploy Ghost on Railway Using Github Actions with Railway Deploy Calendso (cal.com) on Railway Self-hosted website analytics Use Notion as a CMS for your NextJS blog
Building a NestJS App on Railway
olabemiwo daniel · 2024-12-13 · via Railway Blog

Avatar of olabemiwo daniel

olabemiwo daniel

Nestjs is a javascript framework with a typescript flavour. Often described as the swiss-army of javascript backend applications, it allows you to write following an object-oriented programming paradigm or functional programming and is easily a good switch for anyone coming from a non-js background to make the switch.

This article covers the nitty gritty of getting out Nestjs running on Railway. Here is the link to the project we will build in GitHub.

Let's get started.

Create a new Nestjs Project

You can use your preferred cli tool on your machine to get started.

To create a new project, just type the commands below sequentially

  • Install nestjs:
npm i -g @nestjs/cli
  • Create a new nestjs project:
nest new rail-nest

The project name is rail-nest which can be replaced with any name you like.

  • Run the command below to enter the new project directory and start the nestjs project locally on your machine:
cd rail-nest
npm run start

If you navigate to http://localhost:3000 on your browser, you should get a positive response showing your nestjs application is running.

Add a Dockerfile

To have an application that can easily scale, where we can continually add more components as our application grows, containerization is a great approach to ensuring we can have an all-in-one application.

To get started, we need to create a Dockerfile, where we can add detailed instructions for our Docker applications.

  • In your cli, run the command below to create a Dockerfile and a .dockerignore in your project root directory.
touch Dockerfile .dockerignore
  • Then let's add the instruction below to the Dockerfile
# Base image
FROM node:20

# Create app directory
WORKDIR /usr/src/app

# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./

# Install app dependencies
RUN npm ci

# Bundle app source
COPY . .

# Creates a "dist" folder with the production build
RUN npm run build

# Expose the port on which the app will run
EXPOSE 3000

# Start the server using the production build
CMD ["npm", "run", "start:prod"]
  • Add the following to your .dockerignore.
Dockerfile
 .dockerignore
node_modules
npm-debug.log
Dist

Deploy to Railway

Now let’s deploy the project to Railway. See Railway docs for reference if needed.

  • Push the NestJS code to a github repo.
  • On your project canvas in Railway
    • Create a new project
    • Add a new Github service
    • Select your Github repo
    • Connect your github repo to the source repo in the source section.
    • Apply changes to deploy the app

Setup the app database, cache, and task scheduler

The setup ensures that the database, migrations, queues and scheduled tasks are all operational and can run seamlessly.

Setup the cache manager

We will start by using the Nestjs cache manager, the native cache manager stores the cache in memory, we will then configure the cache to be stored in Redis.

  • Install this cache manager package via your cli:
npm install @nestjs/cache-manager cache-manager@5.1.1 @nestjs/config
  • Then import the CacheModule into yourapp.module.ts:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CacheModule } from '@nestjs/cache-manager';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
	ConfigModule.forRoot(),
	CacheModule.register()
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Implement the cache module globally (Optional)

If you want to leverage the cache module across different modules, you can pass the isGlobal flag property:

CacheModule.register({ isGlobal: true })

For example, here's a CacheModule implementation applied globally to a NestJS app in the app.module.ts file:

import { CacheModule, Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot(),
    CacheModule.register({
      isGlobal: true,
    }),
  ],
})
export class AppModule {}

Implement Redis for caching

Up to this point, our cache will be stored in memory, to migrate easily to Redis, we will need to update the cache module configuration and also create a Redis server in Railway.

  • Let's install the relevant packages:
npm install cache-manager-redis-store@3.0.1
npm install --save-dev @types/cache-manager-redis-store
  • Now, proceed to change the cache module to use Redis.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CacheModule } from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-redis-store';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot(),
    CacheModule.register({
    isGlobal: true,
    store: redisStore,
    host: process.env.REDISHOST,
    port: process.env.REDISPORT
  })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • After, we will tweak our cache module to the instruction below:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { CacheModule, CacheStore } from '@nestjs/cache-manager';
import { redisStore } from 'cache-manager-redis-store';

@Module({
  imports: [
    ConfigModule.forRoot(),
    CacheModule.registerAsync({
      isGlobal: true,
      useFactory: async () => {
        const store = await redisStore({
          socket: {
            host: process.env.REDISHOST,
            port: +process.env.REDISPORT,
          },
          url: process.env.REDISURL,
          password: process.env.REDISPASSWORD
        });
        return {
          store: store as unknown as CacheStore,
          ttl: 60 * 60 * 24 * 7,
        }
      }
    })
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

All set locally, simply push to your github repo the latest changes.

Add Redis to the Railway project

Now let’s add a Redis service in Railway and connect it to NestJS.

  • On your railway project canvas, create a new redis service.
  • Head back to your App service and click on Variables.
  • Add all necessary environment variables
REDISHOST="${{Redis.REDISHOST}}"
REDISPASSWORD="${{Redis.REDIS_PASSWORD}}"
REDISPORT="${{Redis.REDISPORT}}"
REDISURL="${{Redis.REDIS_URL}}"
  • Click Deploy
View of NestJS project in Railway with Redis
View of NestJS project in Railway with Redis

Adding Postgres

Currently, we have Redis infused into our Nestjs app. Let's add the postgres database.

  • Locally, we are going to add typeorm and the postgres adapter package.
npm install @nestjs/typeorm typeorm
npm install pg
  • Then add the following in our app.module.ts
	TypeOrmModule.forRootAsync({
      useFactory: () => ({
        type: 'postgres',
        host: process.env.POSTGRESHOST,
        port: +process.env.POSTGRESPORT,
        username: process.env.POSTGRESUSER,
        password: process.env.POSTGRESPASSWORD,
        database: process.env.POSTGRESDB,
        synchronize: true,
        entities: []
      })
    })

Note the values in the env are random variables and should be replaced with their original representation based on your setup.

  • Simply push to your github repo the latest changes.

Add Postgres to the Railway project

Now let’s add the Postgres service to our Railway project and connect it to NestJS.

  • On your railway project canvas, create a new Postgres service.
  • Head back to your App service and click on Variables.
  • Add all necessary environment variables
POSTGRESDB="${{Postgres.PGDATABASE}}"
POSTGRESHOST="${{Postgres.PGHOST}}"
POSTGRESPASSWORD="${{Postgres.PGPASSWORD}}"
POSTGRESPORT="${{Postgres.PGPORT}}"
POSTGRESUSER="${{Postgres.PGUSER}}"
  • Click Deploy
View of NestJS project in Railway with Postgres
View of NestJS project in Railway with Postgres

Adding a task scheduler

Let us add a task scheduler in Nestjs.

  • Installing the packages below:
npm install --save @nestjs/schedule
npm install --save-dev @types/cron
  • Add the instruction below to your app.module.ts import section:
ScheduleModule.forRoot()

Nestjs schedule runs alongside your main application, by integrating the cron functionality directly into the application lifecycle.

  • A final push to the github repo and our setup is complete.

Set up a Public URL

Let’s make the NestJS app available on the public internet.

  • Navigate to the Networking section under the Settings tab of your new service.
  • Click Generate Domain to create a public URL for your app.

We now have a fully functional Nestjs application running in Railway!

Let’s explore one more option for starting a NestJS project in Railway.

One-Click Deploy from a Template

Railway provides templates as a way to get started almost immediately with your NestJS project, enabling you to provision a service or set of services by simple clicks.

If you’re looking for the fastest way to get started, the one-click deploy option is ideal. It sets up your Nestjs app along with a Redis database, a Postgres database and the Nestjs scheduler. Just click the button below to get started.

Deploy on Railway

After deploying, we recommend that you eject from the template to create a copy of the repository under your own GitHub account. This will give you full control over the source code and project.

Conclusion

With that, we've successfully set up a Nestjs application coupled with everything needed to get started immediately, database, caching and cron schedule inclusive. You should also be able to use this as a reference to deploy your Nestjs application from scratch or via Github. There is no limit to what you can do, and can decide to extend to other Railway compatible service.