1 Preface
In the articleDocker starts PostgreSQL and recommends several connection tools》We introduce how to passDocker
Come to startPostgreSQL
, but only one database, if you want to create multiple databases in the sameDocker
What to do on the container?
2 Two solutions
One solution is toshell/sql
Put scripts in//
In the directory, let the container be automatically created when it starts; the other is throughshell
Scripts are created in nature, and they are essentially the same. Only the first one is introduced here.
Bundleshell
Script orsql
When the script is placed in the specified directory, it will be executed automatically, and both scripts are OK.
shell
Examples of scripts are as follows:
#!/bin/bash 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; 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
sql
Examples of scripts are as follows:
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;
3 Package startup
PrepareDockerfile
,Bundleshell/sql
Put the script file into the image:
FROM postgres:10 COPY src/main/resources/ // COPY src/main/resources/ //
Start 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-databases:1.0-SNAPSHOT
After successful startup, the following database will be created:
db1,db2, logdata,orderdata,userdata
4 Summary
This is a solution used during the development testing phase, and actually putting the database in a container is not a good choice.
Please check the code:/LarryDpk/pkslow-samples
This is the article about creating multiple databases when Docker starts PostgreSQL. For more related content on Docker starts PostgreSQL, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!