How to Set Up PostgreSQL with NestJS and Docker for Fast Local Development: A Quick Guide
This article outlines the process of setting up a local development environment using Docker for NestJS applications with PostgreSQL, without the need for a production database provider.
This article outlines the process of setting up a local development environment using Docker for NestJS applications with PostgreSQL, without the need for a production database provider.
The following files are required for the setup:
Dockerfile for the NestJS application docker-compose.yml to configure Node.js and PostgreSQL .env file for environment variables Sample NestJS configuration and scripts
docker-compose.yml: Node and PostgreSQL Integration
services: db: image: postgres:13 restart: always env_file:
ports:
volumes:
- .env
- "5432:5432"
- db-data:/var/lib/postgresql/data
api: build: context: . dockerfile: Dockerfile ports:
depends_on:
env_file:
command: sh -c "npm run migration:run && npm run start:dev"
- "3000:3000"
- db
- .env
volumes: db-data:
Note: Using the volumes key allows the database to retain data across reboots.
Create a .env file at the root of your project with the following content:
POSTGRES_USER=postgres POSTGRES_PASSWORD=changeme POSTGRES_DB=app_db POSTGRES_HOST=db POSTGRES_PORT=5432 PORT=3000
Important: Ensure .env is included in .gitignore to protect sensitive information.
Package.json Scripts for Container Management
Add these scripts to your package.json for easier container access:
"scripts": { "db": "docker exec -it $(docker-compose ps -q db) bash", "api": "docker exec -it $(docker-compose ps -q api) bash" }
Use npm run db for the database container shell and npm run api for the application container.
NestJS: Database Connection Configuration
In your main startup file (e.g., main.ts ):
async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(process.env.PORT); } bootstrap();
Database Configuration:
A typical configuration file for TypeORM:
const config = { type: "postgres", host: process.env.POSTGRES_HOST, port: parseInt(process.env.POSTGRES_PORT, 10), username: process.env.POSTGRES_USER, password: process.env.POSTGRES_PASSWORD, database: process.env.POSTGRES_DB, entities: [__dirname + "/**/*.entity{.ts,.js}"], synchronize: false, migrations: [__dirname + "/migrations/**/*{.ts,.js}"], autoLoadEntities: true, };
Start all services: docker-compose up --build (initial) or docker-compose up View logs: docker-compose logs -f api Stop and remove containers: docker-compose down Access the database shell: npm run db Access the application container: npm run api
Based on reporting by hackernoon.com.
