Use PostgreSQL, and TypeORM with Nest JS backend framework. Set up PostgreSQL on Docker with a docker-compose.yml file.
Create Nest App
nest new twitter-app-api
Install dependencies
npm install @nestjs/typeorm typeorm pg or yarn add @nestjs/typeorm typeorm pg
Setup PostgreSQL using Docker
Docker Compose setup for NestJS application with TypeORM and PostgreSQL
Create a .env file in the root of the project folder
POSTGRES_DB=twitter_db POSTGRES_USER=twitter_user POSTGRES_PASSWORD=twitter_password POSTGRES_PORT=5432 POSTGRES_HOST=localhost
docker-compose.yml – Add to the project root folder
services: postgres: image: postgres:latest container_name: twitter_postgres_db ports: - '5432:5432' environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data:
Run Docker Command from the project root folder
docker compose up -d
Connect DB using credentials
Create Database Module
nest g module database
// src/database/database.module.ts import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot(), TypeOrmModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ type: 'postgres', host: configService.get('POSTGRES_HOST'), port: configService.get('POSTGRES_PORT'), username: configService.get('POSTGRES_USER'), password: configService.get('POSTGRES_PASSWORD'), database: configService.get('POSTGRES_DB'), entities: [__dirname + '/../**/*.entity{.ts,.js}'], synchronize: true, // TODO: set to false in production }), inject: [ConfigService], }), ], }) export class DatabaseModule {}