---
title: "Cara Deploy NestJS ke Helipod: Backend TypeScript Production-Ready"
url: "https://helipod.io/blog/cara-deploy-nestjs-ke-helipod"
date: "2026-05-03"
updated: "2026-05-03"
author: "Tim Helipod"
tags: ["nestjs", "nodejs", "typescript", "backend", "tutorial", "deployment"]
excerpt: "Cara deploy NestJS ke Helipod: Helipack auto-detect backend TypeScript, generate Dockerfile optimal, dan langsung live tanpa konfigurasi server."
---

# Cara Deploy NestJS ke Helipod: Backend TypeScript Production-Ready

NestJS adalah framework Node.js berbasis TypeScript yang paling banyak dipakai untuk membangun backend API yang scalable dan maintainable. Arsitektur modular ala Angular-nya membuat codebase tetap rapi meski project berkembang besar.

Tapi deploy NestJS ke production punya kerumitannya sendiri: build TypeScript ke JavaScript, setup environment yang benar, pastikan `dist/` ter-copy dengan benar, dan konfigurasi port yang tepat.

Helipod mengurus semua itu lewat **Helipack**: otomatis deteksi NestJS, run `npm run build`, dan serve hasil build dari `dist/main.js`.

## Yang Kamu Butuhkan

- Akun Helipod (daftar gratis di [helipod.io](https://helipod.io))
- Repository NestJS di GitHub atau GitLab
- NestJS 9+ (semua versi modern didukung)

## Persiapan Project NestJS

### 1. Pastikan script build ada di package.json

```json
{
  "scripts": {
    "build": "nest build",
    "start:prod": "node dist/main",
    "start": "node dist/main"
  }
}
```

Helipack mendeteksi script `build` dan menjalankannya otomatis.

### 2. Konfigurasi Port dari Environment Variable

Di `src/main.ts`, pastikan port dibaca dari environment:

```typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // Baca PORT dari environment, default 3000
  const port = process.env.PORT || 3000;
  
  await app.listen(port, '0.0.0.0');
  console.log(`Application running on port ${port}`);
}
bootstrap();
```

> **Penting:** Pastikan listen di `'0.0.0.0'`, bukan `'localhost'`. Container Docker membutuhkan ini agar bisa diakses dari luar.

### 3. Konfigurasi CORS (Jika Dibutuhkan)

```typescript
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  // atau konfigurasi lebih spesifik:
  app.enableCors({
    origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
    credentials: true,
  });
  
  await app.listen(process.env.PORT || 3000, '0.0.0.0');
}
```

## Langkah 1: Connect Repository

Login ke dashboard Helipod, klik **New Project**, pilih repository NestJS dari GitHub atau GitLab.

Helipack mendeteksi NestJS dari `package.json`: melihat dependency `@nestjs/core` dan script `build`.

## Langkah 2: Set Environment Variables

Buka tab **Variables** dan tambahkan environment variables yang dibutuhkan:

```env
NODE_ENV=production
PORT=3000

# Database (jika menggunakan TypeORM + PostgreSQL)
DB_HOST=nama-service-postgres
DB_PORT=5432
DB_NAME=nestdb
DB_USER=postgres
DB_PASSWORD=secret

# JWT (jika menggunakan auth)
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d

# Redis (jika menggunakan caching/queue)
REDIS_HOST=nama-service-redis
REDIS_PORT=6379
```

> **Internal Network:** `DB_HOST` dan `REDIS_HOST` menggunakan nama service di canvas Helipod. Baca [Panduan Internal Network](/blog/internal-network-pod-to-pod-helipod) untuk detail.

## Langkah 3: Deploy

Klik **Deploy**. Helipack akan:

1. Detect NestJS dari `package.json`
2. Install semua dependencies (`npm ci`)
3. Run `npm run build` (compile TypeScript → JavaScript)
4. Copy `dist/` ke production image
5. Install **production dependencies only** di final image
6. Deploy dengan `node dist/main.js`

## Dockerfile yang Dihasilkan Helipack

Helipack menggunakan multi-stage build untuk NestJS, hasilnya image yang kecil karena tidak menyertakan devDependencies dan TypeScript compiler:

```dockerfile
# syntax=docker/dockerfile:1
FROM node:20-alpine AS base
RUN apk add --no-cache libc6-compat tini git
WORKDIR /app

FROM base AS deps
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci --prefer-offline --no-audit --no-fund

FROM base AS prod-deps
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci --prefer-offline --no-audit --no-fund --omit=dev

FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NODE_OPTIONS="--max-old-space-size=4096"
RUN --mount=type=cache,target=/root/.npm \
    --mount=type=secret,id=build_env,dst=/app/.env \
    npm run build

FROM base AS runner
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 appgroup && \
    adduser  --system --uid 1001 appuser

COPY --from=builder   --chown=appuser:appgroup /app/dist         ./dist
COPY --from=prod-deps --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --chown=appuser:appgroup package.json ./

USER appuser
EXPOSE 3000
ENV PORT=3000 HOSTNAME=0.0.0.0
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "dist/main"]
```

Multi-stage build ini memastikan TypeScript compiler (`typescript`, `ts-node`, `@types/*`) tidak ikut masuk ke production image.

## Langkah 4: Verifikasi

Setelah **LIVE**, test endpoint API kamu:

```bash
curl https://nama-project.helipod.app/
curl https://nama-project.helipod.app/api/health
```

Pantau di tab **Metrics** untuk memastikan memory usage normal (NestJS biasanya butuh 150-300MB RAM untuk aplikasi medium).

## Setup dengan Database TypeORM

Jika menggunakan TypeORM, konfigurasi `ormconfig` lewat environment variables:

```typescript
// app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT || '5432'),
      username: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: process.env.NODE_ENV !== 'production', // JANGAN synchronize di production!
      migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
      migrationsRun: true, // jalankan migrasi otomatis saat startup
    }),
  ],
})
export class AppModule {}
```

Dengan `migrationsRun: true`, TypeORM otomatis menjalankan migrasi pending setiap kali aplikasi start, tidak perlu manual jalankan dari terminal.

## Setup dengan Prisma

Jika menggunakan Prisma ORM:

```env
DATABASE_URL=postgresql://postgres:password@nama-service-postgres:5432/nestdb
```

Tambahkan script di `helipack.json` untuk otomatis generate Prisma client dan jalankan migrasi:

```json
{
  "run": {
    "port": 3000,
    "before": "npx prisma migrate deploy"
  },
  "health": {
    "path": "/api/health",
    "duration": 20
  }
}
```

Dan pastikan `prisma generate` dijalankan saat build, tambahkan ke `package.json`:

```json
{
  "scripts": {
    "build": "prisma generate && nest build"
  }
}
```

## Konfigurasi Health Check

Tambahkan endpoint health check di NestJS untuk Helipod:

```typescript
// health.controller.ts
import { Controller, Get } from '@nestjs/common';

@Controller('api/health')
export class HealthController {
  @Get()
  check() {
    return { status: 'ok', timestamp: new Date().toISOString() };
  }
}
```

Lalu di `helipack.json`:

```json
{
  "health": {
    "path": "/api/health",
    "duration": 15
  }
}
```

Helipod akan menggunakan endpoint ini untuk menentukan kapan pod sudah siap menerima traffic.

## Konfigurasi Lanjutan dengan helipack.json

```json
{
  "run": {
    "port": 3000,
    "before": "npx prisma migrate deploy",
    "command": "node dist/main"
  },
  "health": {
    "path": "/api/health",
    "duration": 20
  },
  "spec": {
    "cpu": 0.5,
    "memory": 512
  }
}
```

## Tips Performa NestJS di Production

**Gunakan compression middleware:**
```typescript
import * as compression from 'compression';
app.use(compression());
```

**Enable helmet untuk security headers:**
```typescript
import helmet from 'helmet';
app.use(helmet());
```

**Graceful shutdown:**
```typescript
app.enableShutdownHooks();
```

Ini penting agar NestJS selesaikan request yang sedang berjalan sebelum container di-stop saat redeploy.

## Troubleshooting Umum

**Build error: "Cannot find module '@nestjs/core'"**
Pastikan `@nestjs/core` ada di `dependencies`, bukan `devDependencies`.

**Port tidak bisa diakses**
Pastikan `main.ts` listen di `'0.0.0.0'`, bukan `'localhost'` atau tanpa parameter kedua.

**TypeORM "connection refused"**
Cek `DB_HOST` sudah menggunakan nama service PostgreSQL di Helipod, bukan `localhost`.

**"Cannot find module './dist/main'"**
Pastikan `npm run build` berhasil. Cek Build logs untuk error TypeScript compile.

## Kesimpulan

Deploy NestJS ke Helipod semudah push ke GitHub. Helipack mengurus TypeScript compilation, multi-stage build, dan konfigurasi production server secara otomatis.

Butuh setup Redis untuk caching atau BullMQ untuk job queue? Tambahkan service Redis di canvas Helipod dan hubungkan via [Internal Network](/blog/internal-network-pod-to-pod-helipod).

Punya pertanyaan? Hubungi kami di [support@helipod.io](mailto:support@helipod.io) atau bergabung ke komunitas di [hangar.helipod.io](https://hangar.helipod.io).
