Liverpool
Liverpool

Reputation: 275

How to create a docker container which every night make a backup of mysql database?

Hello i have created mysql image and with this command

docker run --name db-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest  --> Run container with my sql

docker pull mysql --> create image with mysql

docker run --name db_mysql-e MYSQL_ROOT_PASSWORD=1234 -e MYSQL_DATABASE=mami -p 3306:3306 -d mysql

i execute it but after that i don't know what to do and how to make a DB in this container and the job for the backup

If someone can help me with step by step what to do

Upvotes: 6

Views: 9351

Answers (1)

Thomasleveil
Thomasleveil

Reputation: 103915

You could use the cron service from your host system to run the following command as described in the documentation for the mysql docker image:

crontab example for running the command every night at 2:00 am:

00 02 * * * /usr/bin/docker exec db-mysql sh -c 'exec mysqldump --all-databases -uroot -p"my-secret-pw"' > /some/path/on/your/host/all-databases.sql

Alternatively you could run another container designed just for this task such as deitch/mysql-backup:

docker run --name db-mysql -d \
    -e MYSQL_ROOT_PASSWORD=my-secret-pw \
    -e MYSQL_USER=my-user \
    -e MYSQL_PASSWORD=my-user-password \
    -e MYSQL_DATABASE=my-db \
    mysql:latest

docker run -d --restart=always \
    --name=db-backup \
    -e DB_DUMP_BEGIN=0200 \
    -e DB_SERVER=db-mysql \
    -e DB_USER=my-user \
    -e DB_PASS=my-user-password \
    -e DB_NAMES=my-db \
    -e DB_DUMP_TARGET=/db \
    -v /somewhere/on/your/host/:/db \
    databack/mysql-backup

You also need to make sure the /somewhere/on/your/host/ folder is writable by users of group 1005:

sudo chgrp 1005 /somewhere/on/your/host/
sudo chmod g+rwX /somewhere/on/your/host/

But this container must have a mean to connect to your db-mysql container. For that you create a docker network and connect both containers to it:

docker network create mysql-backup-net
docker network connect mysql-backup-net db-backup
docker network connect mysql-backup-net db-mysql

Upvotes: 5

Related Questions