Skip to content

Add user + password per database entry #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ mechanism.
### By mounting a volume

Clone the repository, mount its directory as a volume into
`/docker-entrypoint-initdb.d` and declare database names separated by commas in
`POSTGRES_MULTIPLE_DATABASES` environment variable as follows
`/docker-entrypoint-initdb.d` and declare database names separated by commas and each entry with database, user and password separated by double colon in `POSTGRES_MULTIPLE_DATABASES` environment variable as follows
(`docker-compose` syntax):

myapp-postgresql:
image: postgres:9.6.2
volumes:
- ../docker-postgresql-multiple-databases:/docker-entrypoint-initdb.d
environment:
- POSTGRES_MULTIPLE_DATABASES=db1,db2
- POSTGRES_MULTIPLE_DATABASES=db1:user:pwd,db2:user:pwd
- POSTGRES_USER=myapp
- POSTGRES_PASSWORD=
- POSTGRES_DB=db

### By building a custom image

Expand All @@ -48,10 +48,11 @@ to the container:
- POSTGRES_MULTIPLE_DATABASES=db1,db2
- POSTGRES_USER=myapp
- POSTGRES_PASSWORD=
- POSTGRES_DB=db

### Non-standard database names

If you need to use non-standard database names (hyphens, uppercase letters etc), quote them in `POSTGRES_MULTIPLE_DATABASES`:

environment:
- POSTGRES_MULTIPLE_DATABASES="test-db-1","test-db-2"
- POSTGRES_MULTIPLE_DATABASES="test-db-1:user:pwd","test-db-2:user:pwd"
15 changes: 9 additions & 6 deletions create-multiple-postgresql-databases.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ set -e
set -u

function create_user_and_database() {
local database=$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;
local dbinfo=$1
IFS=":" read -r database user password <<< "$dbinfo"

echo "Creating database '$database' with user '$user' and password '$password'"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
CREATE USER $user;
ALTER USER $user WITH ENCRYPTED PASSWORD '$password';
CREATE DATABASE $database;
GRANT ALL PRIVILEGES ON DATABASE $database TO $user;
EOSQL
}

Expand Down