In a Spring Boot app, I am trying to initialize databases for the business services and have tried several methods using init.sql and init-dbs.sh scripts with different options and parameters. However, in each time, databases are not created and I think problem may be caused from converting t6he script to executable.
I also use Liquibase in my project, but before creating table phase, I had trouble while creating databases first.
Here is one of the script that I am using and related part of my docker-compose:
init.sh:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE DATABASE inventory_db;
CREATE DATABASE notification_db;
CREATE DATABASE order_db;
CREATE DATABASE payment_db;
CREATE DATABASE product_db;
CREATE DATABASE user_db;
\connect inventory_db
BEGIN;
CREATE USER inventory_user WITH PASSWORD 'inventory_password';
CREATE SCHEMA inventory_schema AUTHORIZATION inventory_user;
COMMIT;
\connect product_db
BEGIN;
CREATE USER product_user WITH PASSWORD 'product_password';
CREATE SCHEMA product_schema AUTHORIZATION product_user;
COMMIT;
\connect user_db
BEGIN;
CREATE USER user_service WITH PASSWORD 'user_password';
CREATE SCHEMA user_schema AUTHORIZATION user_service;
COMMIT;
EOSQL
docker-compose.yml:
services:
postgres:
image: postgres:latest
container_name: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
PGDATA: /var/lib/postgresql/data/pgdata # ???
volumes:
- ./docker/init.sh:/docker-entrypoint-initdb.d/init.sh
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- app-network
I use chmod +x init.sh command to make the script executable and then compose postgres container. But there is not any of these databases created inside this container. So, should I follow another approach or what is the problem with this example?
./docker/init-db.sh:/docker-entrypoint-initdb.d/init-db.shand after your message, I tried to remove the sc script part and update this line with./docker/init-scripts:/docker-entrypoint-initdb.dand worked. Not sure if there would be a better approach or need an update on script or compose file. Thanks.docker-entrypoint-initdb.dis a special directory in the official PostgreSQL Docker image. Scripts (.sql or .sh) placed in this directory will run only when the database directory is empty