Simple PostgreSQL Backup Agent

Dockerized cron job to backup PostgreSQL database or multiple databases on different hosts. It’s based on Alpine docker image, so the image size is less than 11 Mb. The script can be also used without docker and docker compose or as a base for your own dockerized cron jobs. My general recommendation is to run docker container on your backup host to provide a kind of isolation from the management partition.

The script or “agent” does the following:

  • Reads content of /config/passfile to get pg_dump connection parameters
  • Verifies if the backup can be done by executing a dry run for each db
  • If the dry run is completed and plain format set, produces plain-text sql script and compresses it with gzip
  • If the dry run succeeds and custom format set, outputs a custom backup archive (more flexible and by default)
  • Cleans up the storage folder. Files older than 30 days are deleted
  • Redirects all cron job statuses to stdout
  • Keeps backup files under ./psql/backups/{hostname}/{dbname}/ on your host
  • Default settings: twice a day at 8:30 and 20:30 UTC; custom format; clean backups older than 30 days

Current limitations:

  • no encryption for specific databases (in to-do list)
  • no handling of wildcars in passfile (in to-do list)

Content

  • Dockerfile – describes docker image
  • docker-compose.yml – docker compose file to build and run agent service
  • /config/cronfile – cron job schedule settings
  • /config/passfile – PostgreSQL .pgpass actually
  • /config/psql_backup.sh – the script itself

Usage guide

  • check out the passfile and provide your own connection parameters
  • verify the cron job settings in the /config/cronfile
  • change make_backup function argument to set format output (plain/custom)
  • update cleaner function argument at the bottom of the script if necessary
  • edit dockerfile/docker-compose.yml or script itself if necessary
  • run docker compose build
  • run docker compose up -d
  • check out the stoud of the container to get the job’s status
  • TO RESTORE: use psql (if plain set) or pg_restore command (if custom format set)

Dockerfile

FROM alpine:3.16.2
LABEL AUTHOR="Roman Levchenko"
LABEL WEBSITE="rlevchenko.com"
RUN mkdir /etc/periodic/custom \
    && mkdir -p /backup/config \ 
    && touch /var/log/cron.log \
    && apk --no-cache add \
    postgresql14-client=14.5-r0 \
    bash=5.1.16-r2
COPY /config/cronfile /etc/crontabs/root
COPY /config/psql_backup.sh /etc/periodic/custom/backup
COPY ["/config/psql_backup.sh","/config/passfile","/backup/config/"]
RUN chmod 755 /etc/periodic/custom/backup \
    && chmod 0600 /backup/config/passfile
CMD ["-f","-l","8", "-L", "/dev/stdout"]
ENTRYPOINT ["crond"]

Script (excerpt)

# Clean old backup files
function cleaner()
{
set -o pipefail -e
	if [[ -n $(find $BACKUP_DIR \( -name "*.sql.gz" -o -name "*.custom" \) -type f -mtime +"$1") ]]; 
	then
		echo -e "\n${GREEN}[INFO]${OFF} ${BOLD}There are backup files older than $1 days. Cleaning up the following files:${OFF}"
		find $BACKUP_DIR \(-name "*.sql.gz" -o -name "*.custom" \) -print -type f -mtime +"$1" -exec rm {} \;
	else 
		echo -e "\n${GREEN}[INFO]${OFF} ${BOLD}There are no backup files older than $1 days. \nHave a nice day!${OFF}"
	fi
set +o pipefail +e
}

Result

Sample Output (w/error and success messages):

Public preview of Azure Cloud Shell

At the recent Build conference, Microsoft officially announced public preview of Azure Cloud Shell browser-accessible, pre-configured shell experience for managing Azure resources without the overhead of installing, versioning, and maintaining a machine yourself.

Cloud Shell runs entirely on containers orchestrated by Kubernetes and shows us just another example of how container technology can revolutionize solutions built on Azure.

Machine for Cloud Shell is not persistent and temporary provided on a per-request basis (1 machine per 1 user, permissions are set as a regular Linux user). That machine’s hosting is free. You just need to pay for storage that it consumes (file share –> described later in this post).

Cloud Shell comes with the support of well known tools and languages:

Category Name
Azure Tools Azure CLI 2.0 and 1.0
Linux shell interpreter Bash,sh
Text editors vim,nano,emacs
Containers Docker,Kubectl, DC/OS CLI
Language Version
.NET 1.01
Go 1.7
Node.js 6.9.4
Python 2.7 and 3.5
More: use this link

It supports Bash experience so far. Everyone’s favorite PowerShell is coming soon. You can try the new shell today by pressing the special icon at the top navigation bar of the Azure portal.

azure

The new storage account (LRS), resources group and file share will be created during one-time setup.

  • Resource group is named: cloud-shell-storage-
  • Storage Account: cs-uniqueGuid
  • File Share: cs—com-uniqueGuid

As Cloud Shell’s machine is temporary, file share makes possible to persist your bash $Home directory. This file share will mount as clouddrive under your $Home directory and it’s also used to store a 5 GB image created for you that automatically updates and persists your $Home directory as well (see the pic below, acc_<username>.img).

Note: you pay only for this file share. There are no any  additional compute costs.

SNAGHTML5a54f4

To download/upload files you can use portal as usual. For example, I created txt-file in my clouddrive and would like to download it to my local machine. So, I need to open the file share associated with cloud shell, locate the file “text.txt” and just hit “Download”.

To add some files from local machine to clouddrive, use the “Upload” button and then check result by running cd clouddrive and  ls in the cloud shell session

SNAGHTML7097ce

As you may noticed, Cloud Shell automatically authenticates on each session for instant access to your resources through the Azure CLI 2.0. You can even use the interactive mode for Azure CLI 2.0 to ease scripting and save a lot of time

azure shell

Each cloud shell session times out after 10 minutes without any activities

image

That’s great, but that is not the whole news

Cloud Shell is also embedded directly in docs.microsoft.com and it makes Azure CLI samples in documentation fully interactive. To evaluate this new functionality, go to Azure CLI 2.0 documentation, log in to Cloud Shell by clicking “Try it” and start learning in just a new way.

azure cloud shell and docs

Some more examples

Creating VM in the cloud shell

SNAGHTMLa23890

List of VMs in the resource group with customized output

SNAGHTMLb64914

%d bloggers like this: