In my recent Node.js project, I set up a PostgreSQL database using Prisma ORMâone of the most efficient and type-safe ORMs available. I used docker to run postgres on my linux machine
Hereâs a detailed walkthrough of the setupâfrom pulling the Docker image to generating the Prisma client. If you’re getting started with Prisma and PostgreSQL in Node.js, this guide is for you.
đ ïž Prerequisites
Make sure the following are installed:
Step 1: Pull PostgreSQL Docker Image
docker pull postgres
Step 2: Run PostgreSQL Container
docker run --name my-postgres -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb -p 5432:5432 -d postgres
đ This sets up a PostgreSQL container with:
- Username: admin
- Password: secret
- Database name: mydb
- Port: Exposes DB on localhost:5432
Step 3: Init NodeJs project
npm init -y
Step 4: Install Prisma
npm install prisma --save-dev
npm install @prisma/client
npx prisma init
đ Step 5: Configure .env
add DATABASE_URL in .env file
DATABASE_URL="postgresql://admin:secret@localhost:5432/mydb?schema=public"
- admin: PostgreSQL username
- secret: PostgreSQL password
- localhost: Host of the DB server
- 5432: PostgreSQL’s default port
- mydb: Database name
- schema=public: Default schema in PostgreSQL
đ Step 6: Define Your Prisma Schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
}
âïž Step 7: Migrate and Generate Prisma Client
npx prisma migrate dev --name init
npx prisma generate
—
migrate dev creates migration files and updates the DB
generate creates the Prisma client for querying
Step 8: Test the Database Connection
Letâs write a quick script to ensure everythingâs working as expected.
Create a script.js file:
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
const user = await prisma.user.create({
data: {
email: 'abc@example.com',
name: 'Tushar',
},
});
console.log('User created:', user);
const allUsers = await prisma.user.findMany();
console.log('All users:', allUsers);
}
main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Run the Script
node script.js
You should see something like:
User created: { id: 1, email: 'abc@example.com', name: 'Tushar', createdAt: 2025-05-18T... }
All users: [ { id: 1, email: 'abc@example.com', name: 'Tushar', createdAt: 2025-05-18T... } ]
đ Congratulations! You’ve successfully connected Node.js to a PostgreSQL database running inside a Docker container using Prisma.