Skip to content

Commit 5a1be4f

Browse files
committed
Add script and README
1 parent 179bb2f commit 5a1be4f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Using multiple databases with official PostgreSQL Docker image
2+
3+
The [official recommendation](https://hub.docker.com/_/postgres/) for creating
4+
multiple databases is as follows:
5+
6+
*If you would like to do additional initialization in an image derived from
7+
this one, add one or more `*.sql`, `*.sql.gz`, or `*.sh` scripts under
8+
`/docker-entrypoint-initdb.d` (creating the directory if necessary). After the
9+
entrypoint calls `initdb` to create the default `postgres` user and database,
10+
it will run any `*.sql` files and source any `*.sh` scripts found in that
11+
directory to do further initialization before starting the service.*
12+
13+
This directory contains a script to create multiple databases using that
14+
mechanism.
15+
16+
## Usage
17+
18+
Clone the repository, mount it's directory into the official Docker image and
19+
declare database names separated by commas in `POSTGRES_MULTIPLE_DATABASES`
20+
environment variable as follows (`docker-compose` syntax):
21+
22+
myapp-postgresql:
23+
image: postgres:9.6.2
24+
volumes:
25+
- ../docker-posgresql-multiple-databases:/docker-entrypoint-initdb.d
26+
environment:
27+
- POSTGRES_MULTIPLE_DATABASES=db1,db2
28+
- POSTGRES_USER=myapp
29+
- POSTGRES_PASSWORD=
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/bin/bash
2+
3+
set -e
4+
set -u
5+
6+
function create_user_and_database() {
7+
local database=$1
8+
echo " Creating user and database '$database'"
9+
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
10+
CREATE USER $database;
11+
CREATE DATABASE $database;
12+
GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
13+
EOSQL
14+
}
15+
16+
if [ $POSTGRES_MULTIPLE_DATABASES ]; then
17+
echo "Multiple database creation requested: $POSTGRES_MULTIPLE_DATABASES"
18+
for db in $(echo $POSTGRES_MULTIPLE_DATABASES | tr ',' ' '); do
19+
create_user_and_database $db
20+
done
21+
echo "Multiple databases created"
22+
fi

0 commit comments

Comments
 (0)