Tuesday, September 8, 2015

A quick way to run Postgres in Docker with local directory data storage

There are a lot of times where I want to quickly spin up a postgres server for some testing.

Unfortunately this usually involves installing it in the package manager and working with the global postgres config. Running postgres in Docker is better but volumes are tricky to deal with, and using data containers means you have to keep track of an extra container, as well as remembering to clean up volumes that are no longer used.

So I wrote this quick script that does all the steps needed to run a postgres docker container using a local directory for data storage, instead of volumes. So instead of having to leave your TestWebAppPostgresDb container and TestDataProcessingPostgresDb container hanging around in docker you can just leave them in local directories.

Quick usage

#Build the docker image
sudo docker build -t stevechy/postgres:v9.3 [DirectoryWithDockerFile]

#Make a database directory
mkdir -p projects/testDatabases/mytestdb

#Copy runDockerPostgres.py to the directory, or symlink it
cp runDockerPostgres.py projects/testDatabases/mytestdb

#Grab the default /etc/postgresql config from the docker image
cd projects/testDatabases/mytestdb
./runDockerPostgres.py --action extractEtcPostgresql

#Configure etc_postgresql/9.3/main/postgresql.conf if needed, for example, setting the port

#Initialize the postgres data cluster
./runDockerPostgres.py --action initDb

#You'll need a running postgres to create databases and users, start postgres in another terminal
./runDockerPostgres.py --action run

#Create a user
./runDockerPostgres.py --action createuser
#Enter name of role to add: testuser
#Enter password for new role: 
#Enter it again: 
#Shall the new role be a superuser? (y/n) n
#Shall the new role be allowed to create databases? (y/n) n
#Shall the new role be allowed to create more new roles? (y/n) n

#Create a database
./runDockerPostgres.py --action createdb --dbowner testuser --dbname testdb

You should now have a local running postgres that you can connect to.


from debian:wheezy

RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ wheezy-pgdg main" > /etc/apt/sources.list.d/pgdg.list
RUN apt-get update

RUN apt-get -y install wget ca-certificates

RUN wget --quiet https://www.postgresql.org/media/keys/ACCC4CF8.asc ; apt-key add ACCC4CF8.asc

RUN apt-get update

RUN apt-get -y install postgresql-9.3


USER postgres

CMD ["/bin/bash"]