Title: Bootstrapping database creation for a microservice in a container
Slug: bootstrapping-database-creation-for-a-microservice-in-a-container
Date: 2016-07-12 19:45:00
Author: Kartones
Lang: en
Tags: Development, PostgreSQL, Containerization, Databases, Systems-IT, Patterns & Practices
og_image:
Description: Bootstrapping database creation for a microservice in a container, using PostgreSQL for data storage and Linux createdb command for setup.

<p>Today I had to build a new microservice which uses PostgreSQL for data storage. Following the containers principle of disposability instead of reuse, I need to provide some bootstrap logic that setups everything needed for this piece to work independantly and assume that each run might be the first run. Also, following the <a href="http://12factor.net/config" rel="nofollow">Twelve-Factor App config guidelines</a> I shouldn't store any relevant configuration value in files, but use environment variables instead.</p>

<p>What looks simple in theory is indeed simple when you find a solution, but might not be obvious, so here's my approach. I use Linux <a href="http://linux.die.net/man/1/createdb" rel="nofollow">createdb</a> command, but as it doesn't allows you to specify the database connection password as a parameter, I use a .pgpass file with the proper permissions to make it work, with the added bonus of only using bash scripting to achieve it.</p>

<p><pre>
echo "*:*:*:$DB_USER:$DB_PASSWORD" > ~/.pgpass
chmod 0600 ~/.pgpass
createdb $DB_NAME -h $DB_HOST -p $DB_PORT -U $DB_USER -O $DB_USER -w || true
rm ~/.pgpass
</pre></p>

<p>There might be better solutions (I'd love to hear them) but this does the job and is easy to understand.</p>
