Quick Tip: Creating a PostgreSQL Container with default User and Password

beld 🎩
beld 🎩
Apr 30, 2017 · 2 min read

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

.
├── Dockerfile
└── init
└── 01-filladb.sh
cat ./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:

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 👌

beld 🎩

Written by

beld 🎩

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade