Profile PictureKhoi Doan (Osbkca)
Open menu

Build a docker image for backup Mysql database to AWS S3

December 16, 2022

(Updated on April 24, 2023)

article cover

Let’s build a docker image with Dockerfile:

DOCKER
FROM mariadb:latest
WORKDIR /app
RUN apt-get update && apt-get install -y curl unzip python3 python3-venv
RUN ln -s /usr/bin/python3 /usr/bin/python
RUN curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip" && unzip awscli-bundle.zip && ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
COPY backup_to_s3.sh ./backup_to_s3.sh
ENTRYPOINT [ "./backup_to_s3.sh" ]

In this Dockerfile, we use mariadb:latest to call mysqldump . In addition, we also install aws-cli to be able to interact with AWS using the command line.

File backup_to_s3.sh

BASH
#!/bin/bash
# Dump and upload to S3
FILE_NAME=backup-$(date "+%Y-%m-%d-%H%M%S").sql
mysqldump -h $DATABASE_HOST -P 3306 -u $DATABASE_USER --password=$DATABASE_PASSWORD $DATABASE_NAME > $FILE_NAME
aws s3 cp $FILE_NAME s3://$AWS_S3_BUCKET/$FILE_NAME

Don’t forget run chmod a+x backup_to_s3.sh

SHELL
docker build -t backup_mysql:latest .

I have posted this docker image to my Docker Hub account osbkca/backup_mysql

Deploy a CronJob to Kubernetes

mysql-cronjob-backup.yaml

YAML
apiVersion: batch/v1
kind: CronJob
metadata:
labels:
app: auto-backup-mysql
name: auto-backup-mysql
spec:
jobTemplate:
spec:
template:
spec:
affinity: {}
containers:
- env:
- name: DATABASE_HOST
value: <change_value>
- name: DATABASE_USER
value: <change_value>
- name: DATABASE_PASSWORD
value: <change_value>
- name: DATABASE_NAME
value: <change_value>
- name: AWS_S3_BUCKET
value: <change_value>
- name: AWS_ACCESS_KEY_ID
value: <change_value>
- name: AWS_SECRET_ACCESS_KEY
value: <change_value>
image: osbkca/backup_mysql:latest
imagePullPolicy: Always
name: backup-container
schedule: 12 09 * * *
successfulJobsHistoryLimit: 3
suspend: false

To deploy:

BASH
kubectl apply -f mysql-cronjob-backup.yaml

Enjoy it!

With

👍LIKE
❤️LOVE
👏CLAP
🎉PARTY

Updates delivered to your inbox!

A periodic update about my life, recent blog posts, how-tos, and discoveries.

As a thank you, I'll also send you a Free CSS tutorial!

No spam - unsubscribe at any time!


More articles

If you enjoyed this article, you'll find these insightful too!