Deploying a NestJS App
NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It leverages TypeScript by default, provides a modular architecture, and integrates well with modern tools, making it ideal for building robust APIs and microservices.
This guide explains how to deploy a NestJS application to Klutch.sh, both with and without a Dockerfile. It also covers installation and provides sample code to get started.
Prerequisites
- Node.js and npm installed
- Git and GitHub account
- Klutch.sh account
Getting Started: Install NestJS
- Install the NestJS CLI globally:
Terminal window npm install -g @nestjs/cli - Create a new NestJS app:
Terminal window nest new my-nest-appcd my-nest-app - Start the development server:
Your app should be running at http://localhost:3000.
Terminal window npm run start:dev
Sample Code (src/main.ts)
import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';
async function bootstrap() { const app = await NestFactory.create(AppModule); const port = process.env.PORT || 3000; await app.listen(port);}bootstrap();
Deploying Without a Dockerfile
- Push your NestJS app to a GitHub repository.
- Log in to Klutch.sh.
- Create a new project and give it a name.
- Create a new app:
- Select your NestJS GitHub repository and branch
- Set the port to route traffic (usually 3000 for NestJS)
- Choose region, compute, number of instances, and add any environment variables
- Add a start script in your
package.json
:"scripts": {"start": "nest start"} - Click “Create” to deploy. Klutch.sh will build and deploy your app automatically.
Deploying With a Dockerfile
- Add a
Dockerfile
to your project root. Example:# Use official Node.js imageFROM node:18-alpine# Set working directoryWORKDIR /app# Copy package files and install dependenciesCOPY package*.json ./RUN npm install --production# Copy app sourceCOPY . .# Build NestJS appRUN npm run build# Expose port (match your NestJS app)EXPOSE 3000# Start the appCMD ["npm", "run", "start:prod"] - Push your code (with Dockerfile) to GitHub.
- In Klutch.sh, follow the same steps to create a project and app, but select the Dockerfile option when prompted.
- Set the service details and environment variables as needed.
- Click “Create” to deploy. Klutch.sh will build your Docker image and deploy your app.
Note: Your NestJS app should always listen on the PORT
environment variable as shown above.
Resources
Deploying to Klutch.sh is simple and flexible. Choose the method that best fits your workflow and project requirements.