- Init Nest project
- Create Dockerfile
- Create docker-compose.yml
- Create .dockerignore
- Build the containers
- Setting up the PG database
- Install the TypeORM dependencies
- Import TypeORM at the app.module.ts
- Create a new REST module
- Create the user entity
- Inject the user entity on the TypeORMModule (users.module.ts)
- Create the request and response DTOs
- Apply the DTOs on the controllers
- Apply the DTOs on the services
nest new project-name
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD [ "npm", "run", "start:dev"
version: '3.5'
services:
db:
image: postgres
restart: always
environment:
- POSTGRES_PASSWORD=postgres
container_name: postgres
volumes:
- ./pgdata:/var/lib/postgresql/data
ports:
- '7654:7654'
app:
build:
context: .
dockerfile: Dockerfile
container_name: nest-docker-postgres
environment:
- PORT=${PORT}
ports:
- '3000:3000'
depends_on:
- db
volumes:
- ./src:/app/src
pgadmin:
image: dpage/pgadmin4
restart: always
container_name: nest-pgadmin4
environment:
- [email protected]
- PGADMIN_DEFAULT_PASSWORD=pgadmin4
ports:
- '5050:80'
depends_on:
- db
Dockerfile
.dockerignore
node_modules
npm-debug.log
dist
docker compose up --build
To set up your Postgres database you must access http://localhost:5050
(pgadmin) and log in using the credentials you have specified at the docker-compose.yml
file.
In this case, we are going to use the following credentials:
EMAIL=[email protected]
PASSWORD=pgadmin4
After logging in, you must create a new server (Right click Servers > Register > Server), go to the Connection tab and fill in the following fields:
Host name/address: db
Port: 5432
Maintenance database: postgres
Username: postgres
Password: postgres
npm install @nestjs/typeorm typeorm pg class-validators
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'db',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'postgres',
entities: [],
synchronize: true,
autoLoadEntities: true,
}),
],
nest g rest users
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
}
imports: [TypeOrmModule.forFeature([UserEntity])],
import { IsBoolean, IsNotEmpty, IsString } from 'class-validator';
export class CreateUserDto {
@IsString()
@IsNotEmpty()
firstName: string;
@IsString()
@IsNotEmpty()
lastName: string;
@IsBoolean()
isActive: boolean;
}
import { UserEntity } from './../entities/user.entity';
export class ResponseUserDTO {
id: number;
firstName: string;
lastName: string;
isActive: boolean;
constructor(user: Partial<UserEntity>) {
this.id = user.id;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.isActive = user.isActive;
}
}