Setting up drizzle-orm to work with postgres container

Published

I spent quite a few minutes head-scratching at why I couldn't get my drizzle project to talk to my local database running in a docker container via docker-compose working. I remembered that I had faced similar issues last year, but had forgotten what I did to resolve it, so I decided to write this article as a permanent reminder for me & anyone else that may find it useful.

docker-compose file

services:
  db:
    image: postgres
    environment:
      POSTGRES_DB: dbname
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

The important bit here that I was missing was the ports: section.

package.json

{
	"name": "new-project",
	"version": "0.0.1",
	"scripts": {
		"generate": "drizzle-kit generate",
		"migrate": "drizzle-kit migrate",
		"reset": "rm -rf ./drizzle"
	},
	"dependencies": {
		"drizzle-orm": "^0.32.0",
		"postgres": "^3.4.4"
	},
	"devDependencies": {
		"drizzle-kit": "^0.23.0"
	}
}

drizzle configuration

// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
	dialect: "postgresql",
	schema: "./schema.ts",
	out: "./drizzle",
	dbCredentials: {
		url: "postgres://user:[email protected]:5432/dbname"
	}
// migrate.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from 'postgres';
import * as schema from "./schema";


const client = postgres("postgres://user:[email protected]:5432/dbname", { max: 1 });
migrate(drizzle(client, { schema }), { migrationsFolder: "./drizzle" });

Something I didn't bother including in this code dump was having environment variables loaded instead of hardcoding all the user names and passwords, but I just wanted to get this up and running as soon as possible so I didn't even make a .env file myself.