DEV Community

Cover image for Seeding Postgres with Docker
Karan Pratap Singh
Karan Pratap Singh

Posted on

Seeding Postgres with Docker

Seeding postgres container during local development can be bit cumbersome, at least during the initial setup. Usually, we connect to the container and execute the seed script.

But now, let's see how we can automate that by using docker-entrypoint-initdb.d, which runs all the *.sh or *.sql scripts on initialization.

Setup

Let's assume we have this folder structure:

├── Dockerfile
├── docker-compose.yml
└── scripts
    └── db
        ├── dump.sql
        └── init.sh
Enter fullscreen mode Exit fullscreen mode

Here, dump.sql can be sql script that we want to seed the db with

-- CreateTable
CREATE TABLE IF NOT EXISTS users (
  "id" TEXT NOT NULL,
  "name" TEXT NOT NULL,
  "email" TEXT NOT NULL,

  PRIMARY KEY ("id")
);

-- Seed
INSERT INTO users (id, name, email) VALUES ('userid', 'Gopher', 'hello@gopher.com');
Enter fullscreen mode Exit fullscreen mode

In the init.sh, we will just execute our *.sql script.

#!/bin/bash

psql -U $POSTGRES_USER -d $POSTGRES_DB -a -f /app/scripts/db/dump.sql
Enter fullscreen mode Exit fullscreen mode

In the Dockerfile, we will copy our init.sh to docker-entrypoint-initdb.d directory.

FROM postgres:12 as db
WORKDIR /app
COPY ./scripts/db/init.sh /docker-entrypoint-initdb.d
COPY ./scripts/db/dump.sql ./scripts/db/dump.sql
Enter fullscreen mode Exit fullscreen mode

We will define our docker-compose.yml like below:

version: "3.8"

services:
  db:
    image: db
    container_name: db
    build:
      context: .
      target: db
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=database
    ports:
      - 5432:5432
Enter fullscreen mode Exit fullscreen mode

Let's start our containers!

$ docker compose up
Enter fullscreen mode Exit fullscreen mode

Output

output

Conclusion

I hope this was helpful, feel free to reach out to me on twitter if you face any issues. Thanks for reading!

Oldest comments (1)

Collapse
 
rophilogene profile image
Romaric P.

Nice article, a good alternative to seed with postgres is to use Replibyte (open-source) with the local option to seed a postgres db in a container. Cf doc replibyte.com/docs/guides/restore-...