2020-03-02 PostgreSQL on Docker

Lately, I’ve been experimenting with PostgreSQL a lot. It is of course convenient to be able to set up a temporary database to play around. I didn’t want to do it directly on my laptop. One solution was to use Virtualbox (with Vagrant). This is a nice way, and it is even apparently officially supported. (Go to the linked wiki page to learn about various possible reasons why you might want to run PostgreSQL in a VM.)

However, I also wanted to try something different. I am completely new to Docker, and I figured that setting up PostgreSQL in Docker would be a good way to start introducing myself to this technology. I found some instructions on how to run PostgreSQL on Docker here, and the tip worked nicely, with one glitch. The directory I used as a bind mount somehow got its ownership switched to user 999, and having a file owned by someone else in my $HOME felt much like living with a burglar.

It turns out that bind mounts, while (maybe) convenient, just have this problem – a chown in the guest changes the ownership on the host. (This isn’t even very surprising.) The first way I employed to deal with that issue was to use /tmp to mount the PostgreSQL data directory, but this of course doesn’t solve anything. I started to dig (just a little) deeper and found out about volumes, which, according to the linked guide, are the preferred mechanism for persisting data generated by and used by Docker containers. Since I had no reason to have the dockerized PostgreSQL data files in my filesystem, I decided to go with it. So, based on this blog post, here is my way of dockerizing Postgres for experiments:

docker pull postgres
docker run --rm --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5432:5432 --mount 'type=volume,source=pg_data,target=/var/lib/postgresql/data' postgres
psql -h localhost -U postgres -d postgres

Here, pg_data is the name of the volume; you can see the list of your docker volumes with docker volume ls.

(I am pretty sure I could do something to use peer authentication. From a cursory look at the Docker guides, I couldn’t find a way to mount a volume in my host filesystem, but I guess I could just make Docker run sed or something on the Postgres config files so that I wouldn’t have to type the password every time. That will wait until I have some more spare time to learn about Docker.)

Note that the volume is persistent - after killing the container and creating it again, the data are still there. That’s good!

CategoryEnglish, CategoryBlog, CategoryPostgreSQL