Image for post
Image for post

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`):

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:

Script that initializes the Database, a User and grants privileges to this user

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.

Building the image right from the `docker-compose.yml` file

Now, just use docker-compose up to run it. You should see something like this in the end:

Logs from `docker-compose up` showing the initialization

Now, just use `docker-compose up` to run it. You should see something like this in the end:

Creating a table from the container

That’s it! If you have any questions you can reach me at @beld_pro on Twitter at any time 🙌 If you need to upload a file right from your terminal, make sure you also give a try to https://filla.be 👌

Written by

Working on a blog for those indie hackers trying to get servers up — https://ops.tips

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store