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
*.sql scripts on initialization.
Let's assume we have this folder structure:
├── Dockerfile ├── docker-compose.yml └── scripts └── db ├── dump.sql └── init.sh
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', 'email@example.com');
init.sh, we will just execute our
#!/bin/bash psql -U $POSTGRES_USER -d $POSTGRES_DB -a -f /app/scripts/db/dump.sql
Dockerfile, we will copy our
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
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
Let's start our containers!
$ docker compose up
I hope this was helpful, feel free to reach out to me on twitter if you face any issues. Thanks for reading!