1 introduction

If you want to create more than one database on the same Docker container, what do you do?

2 two schemes

One solution is to place shell/ SQL scripts in /docker-entrypoint-initdb.d/ and have the container be created automatically upon startup. The other is specified by shell script, which is essentially the same. Here is only the first.

If you place a shell script or SQL script in a specified directory, it will be executed automatically. Either script will work.

The following is an example shell script:

#! /bin/bash

set -e
set -u

function create_user_and_database() {
	local database=The $1
	echo "  Creating user and database '$database'"
	psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL CREATE USER $database; CREATE DATABASE $database; GRANT ALL PRIVILEGES ON DATABASE $database TO $database; EOSQL
}

if [ -n "$POSTGRES_MULTIPLE_DATABASES" ]; then
	echo "Multiple database creation requested: $POSTGRES_MULTIPLE_DATABASES"
	for db in $(echo $POSTGRES_MULTIPLE_DATABASES | tr ', ' ' '); do
		create_user_and_database $db
	done
	echo "Multiple databases created"
fi
Copy the code

The following is an example of an SQL script:

CREATE USER pkslowuser;

CREATE DATABASE logdata;
GRANT ALL PRIVILEGES ON DATABASE logdata TO pkslowuser;

CREATE DATABASE orderdata;
GRANT ALL PRIVILEGES ON DATABASE orderdata TO pkslowuser;

CREATE DATABASE userdata;
GRANT ALL PRIVILEGES ON DATABASE userdata TO pkslowuser;
Copy the code

3 Package startup

To prepare the Dockerfile, place the shell/ SQL script file in the image:

FROM postgres:10
COPY src/main/resources/create-multiple-postgresql-databases.sh /docker-entrypoint-initdb.d/
COPY src/main/resources/create-multiple-postgresql-databases.sql /docker-entrypoint-initdb.d/
Copy the code

Boot as follows:

docker run -itd \ --name pkslow-postgres \ -e POSTGRES_MULTIPLE_DATABASES=db1,db2 \ -e POSTGRES_USER=pkslow \ -e POSTGRES_PASSWORD=pkslow \ -p 5432:5432 \ pkslow/postgresql-multiple-database: 1.0-snapshotCopy the code

After successful startup, the following database will be created:

db1,db2,
logdata,orderdata,userdata
Copy the code

4 summarizes

This is the scenario used during development testing, and actually putting the database in a container is not a good choice.

Please check the code: github.com/LarryDpk/pk…