Skip to content

Instantly share code, notes, and snippets.

@jirfag
Last active June 1, 2021 03:20
Show Gist options
  • Save jirfag/fefb01bcf015ddf63fbf17f14a4e216c to your computer and use it in GitHub Desktop.
Save jirfag/fefb01bcf015ddf63fbf17f14a4e216c to your computer and use it in GitHub Desktop.
Kubernetes PostgreSQL backups
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: backup
namespace: postgres
spec:
schedule: "0 */12 * * *"
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: db-backup
image: myorg/pg-backuper
env:
- name: BACKUP_DEST
value: s3://my-safe-backups/pg/
- name: PGHOST
value: pg-stolon-proxy.postgres
- name: PGDATABASE
value: api_prod
- name: PGUSER
valueFrom:
secretKeyRef:
name: pg-su
key: username
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: pg-su
key: password
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: aws
key: access_key_id
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws
key: secret_access_key
- name: AWS_REGION
value: us-east-1
FROM python:alpine
RUN pip install --no-cache-dir awscli
RUN apk update && apk add postgresql
COPY dumpDb.sh .
ENTRYPOINT [ "/bin/sh" ]
CMD [ "./dumpDb.sh" ]
mkdir -p /backup
cd /backup
DUMP_FILE_NAME="pg_backup_on_`date +%Y-%m-%d-%H-%M`.dump"
echo "Creating pg dump: $DUMP_FILE_NAME ..."
pg_dump -C -w --format=c --blobs > $DUMP_FILE_NAME
if [ $? -ne 0 ]; then
rm $DUMP_FILE_NAME
echo "Pg back up not created, check db connection settings"
exit 1
fi
echo 'Successfully Backed Up Pg, uploading to AWS S3...'
aws s3 cp $DUMP_FILE_NAME $BACKUP_DEST
echo 'Successfully uploaded to AWS S3'
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment