## Postgres in Docker

From: andrew cooke <andrew@...>

Date: Sat, 24 Jan 2015 09:05:55 -0300

I do nearly all my development these days in Virtual Machines (one per
project, using VirtualBox with the display semalessly integrated into my
desktop).

But sometimes a VM seems like a lot of trouble.  For example (see next post)
I was recently asked to look at how we can generate JSON from Postgres data.
It seems like overkill to install a VM for that, but at the same time I don't
want to use my main machine (I don't think it has the very latest Postgres
version and I want to be able to restart / delete / reset without worrying
what else I might be touching).

So the obvious answer is to use docker.  I installed it from Yast (OpenSuse),
but the general install instructions are here -
https://docs.docker.com/installation/#installation (note that even if you
install from a package manager you may need to (1) start the service and (2)
add your user to the appropriate group).

Once installed, these commands are useful:

# to download the latest docker image
docker pull postgres

The availabe images can be seen at https://registry.hub.docker.com/_/postgres/

# to start the image
docker run --name pg -d postgres

# to connect to the running postgres with psql (interactive)
docker run -it --link pg:postgres --rm postgres \
sh -c 'exec psql -h "$POSTGRES_PORT_5432_TCP_ADDR" -p "$POSTGRES_PORT_5432_TCP_PORT" -U postgres'

# to see what is running
docker ps

# to stop the running postgres
docker kill pg

# to see what is stopped
docker ps -a

# to remove the killed postgres
docker rm pg
# sometimes you also need docker rm XXX where XXX identifies whatever was
# displayed using the previous command

In short, this lets you create a Postgres database that can easily be deleted
and recreated, and where you can play around without worrying about the impact
on anything else.

Andrew