Relocatable PostgreSQL Builds
May 21, 2016
PostgreSQL used to feel somewhat mysterious to me. It tends to live reclusively in an obscure system directory discoverable through programs like
pg_config. Finding the data and log directories for your actual db requires connecting and asking,
psql -c 'show data_directory;'. The daemon runs as another user, and the whole thing is kind of involved. Is there a simpler way, a way to treat Postgres as a regular program that you can run without sudo? The answer is definitely yes.
All you need to do is compile Postgres to be relocatable, and initialize a database in a place of your choosing. The program can be run as a regular user right out of the home directory. The following is adapted from scripts by Brian Cloutier and shows how to compile Postgres from source in Linux and OS X and adjust its binaries to run from any directory.
Building for OS X
First we’ll build a plain Postgres version.
cd /tmp mkdir pg-build # Newest downloads at http://www.postgresql.org/ftp/source/ wget https://ftp.postgresql.org/pub/source/v9.5.3/postgresql-9.5.3.tar.bz2 bunzip2 postgresql-9.5.3.tar.bz2 tar xf postgresql-9.5.3.tar cd postgresql-9.5.3 # Requires xcode to build. # You may also want options such as: # --with-openssl --with-libs=/usr/local/Cellar/readline/6.3.8/lib ./configure --prefix=/tmp/pg-build make make install
Next alter the binaries to use a relative path to libpq.
find /tmp/pg-build/bin -type f | \ xargs -L 1 install_name_tool -change \ /tmp/pg-build/lib/libpq.5.dylib \ '@executable_path/../lib/libpq.5.dylib'
Building for Linux
Once again we start with building the basic binaries.
# I tried this on Ubuntu 16.04 and the resulting binaries work on # many Linux distros but not old ones like CentOS 6 sudo apt-get install -y build-essential libreadline-dev zlib1g-dev bison flex cd /tmp mkdir pg-build wget https://ftp.postgresql.org/pub/source/v9.5.3/postgresql-9.5.3.tar.bz2 bunzip2 postgresql-9.5.3.tar.bz2 tar xf postgresql-9.5.3.tar cd postgresql-9.5.3 # You may also want options such as --with-openssl ./configure --prefix=/tmp/pg-build --disable-rpath # Rather than alter binaries after the fact, we build them referencing # relative paths to libpq export LD_RUN_PATH='$ORIGIN/../lib' make make install
Running without sudo, using local db
The previous steps provide builds in
/tmp/pg-build, hence binaries in
/tmp/pg-build/bin. You can copy and rename the
pg-build directory wherever you want, for instance
cd $HOME cp -R /tmp/pg-build pg mkdir data ./pg/bin/initdb data ./pg/bin/pg_ctl -D data start
Now you’ll have a Postgres instance running as your user and saving information to a directory in your home directory, no sudo necessary. Pretty simple, and nice to see it’s a relocatable program like many others. You can configure this instance by editing the configuration files inside the