Quick Tip: Creating a PostgreSQL Container with default User and Password
Hey, just in case you want to set up a PostgreSQL database with a default user and password using Docker, here’s a very simple way that you can do.
1. Extend the Postgres image to contain an initialization script that will create the user.
From the documentation at https://hub.docker.com/_/postgres/, we can see that it supports adding a set of custom *init* scripts that allow us to initialize databases/users during the bootstrap time. All you’ve gotta do is add your script there and it’ll be ran.
So, that’s what I’ve done: created a `01-filladb.sh` file under `init` and then added that to the right path (`/docker-entrypoint-initdb.d`):
└── 01-filladb.shcat ./DockerfileFROM postgres:alpine
ADD ./init /docker-entrypoint-initdb.d/
2. Add the database initialization to the script
Here is where your initialization code comes: you create the user, create a database and then grant privileges to the first.
As I want to make this extensible (so that I can reuse the image later with other users/databases), everything is parametrized using environment variables:
3. Build and Run
You can either build a usual image (`docker build -t <name> .` — like, `docker build myuser/mytestdb .`) or add a build directive to a `docker-compose.yml` that automatically builds and uses the image.
Now, just use
docker-compose up to run it. You should see something like this in the end:
Now, just use `docker-compose up` to run it. You should see something like this in the end: