Published on

Download a local backup of a Railway database using Docker

Authors

I've recently had to make local backups of a few Postgres databases hosted on Railway, as I was unsure if their recent migration to a paid subscription model would affect any of my hobby projects. Instead of setting up automated backups for test projects, I opted for a quick one-off set-up, just to keep a reserve copy of some of the projects in case they were completely removed.

Using Docker and Docker Compose, I fired up a new image with the relavent postgresql-client, loaded in an .env file with the Postgres database's environment variables (as taken from Railway's dashboard), synced a local folder volume with docker compose, and ran the image with the following shell script:

#!/usr/bin/env bash

set -o errexit

log_msg() {
  echo >&1 "$(date +'%m/%d/%Y %H:%M:%S') - $@"
}

log_msg "Creating backup for: ${PGDATABASE}..."
# create archive if it doesn't exist
mkdir -p ${BACKUP_PATH}
# generate filename
BACKUP_FILENAME="${BACKUP_PATH}/${PGDATABASE}.$(date +'%d-%m-%Y_%H-%M').psqldb.backup"
# export password and run pg_dump
PGPASSWORD="${PGPASSWORD}" pg_dump -U $PGUSER -h $PGHOST -p $PGPORT -W --format=custom $PGDATABASE > "${BACKUP_FILENAME}"
log_msg "Saved backup: ${BACKUP_FILENAME}."

And that's it! A quick and easy local backup for a hosted Postgres database.