Skip to content

Instantly share code, notes, and snippets.

@narate
Created January 26, 2021 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save narate/f1077566f7f267b5b1911bcbe530cea6 to your computer and use it in GitHub Desktop.
Save narate/f1077566f7f267b5b1911bcbe530cea6 to your computer and use it in GitHub Desktop.
Create PostgreSQL user/password wirh database in PostgreSQL running in docker container
#!/bin/sh
# https://github.com/docker-library/postgres/issues/151
set -x
POSTGRES="psql --username ${POSTGRES_USER}"
echo "Before"
echo "======"
$POSTGRES <<-SQL
\du
SQL
echo -n "[*] Creating database role: ${DB_USER}... "
$POSTGRES <<-SQL
CREATE USER ${DB_USER} WITH CREATEDB PASSWORD '${DB_PASSWORD}';
SQL
echo -n "[*] Creating database ${DB_NAME}... "
$POSTGRES <<-SQL
CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};
SQL
echo
echo "After"
echo "====="
$POSTGRES <<-SQL
\du
SQL
@narate
Copy link
Author

narate commented Jan 26, 2021

Usage

Assuming you have a PostgreSQL container running with name = pg_database

with docker command

docker exec -i \
  -e DB_USER=new_user \
  -e DB_PASSWORD=userpwd \
  -e DB_NAME=new_db \
  pg_database sh 2>/dev/null < create-pg-user.sh

with docker-compose command

docker-compose exec -T \
  -e DB_USER=new_user \
  -e DB_PASSWORD=userpwd \
  -e DB_NAME=new_db \
  pg_database sh 2>/dev/null < create-pg-user.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment