1

I found some problem when I used docker exec and mysqldump in cronjob

I wanted to backup my database in container and tried this and it worked well

sudo docker exec -it --user root lemp_mariadb mysqldump -uroot -pxxxxxxx iot  >/home/backup/backup_data.gz

But when I used this in crontab I got file output without anything and the file size is 0 byte

0 24 * * * docker exec -it --user root lemp_mariadb mysqldump -uroot -pxxxxxxx iot >/home/backup/backup_data.gz

What did I do wrong?

nbk
  • 45,398
  • 8
  • 30
  • 47
  • Some more information could really be helpful. I'm assuming that the crontab is running as root? – Dakshraj Sharma Dec 20 '20 at 17:54
  • This looks like a duplicate of: https://stackoverflow.com/questions/37089033/docker-exec-is-not-working-in-cron – Jason Peacock Dec 20 '20 at 18:00
  • Where is the backup being written, does the container have access to where you are attempting to write the file and correct permissions for writing as the user/container? Most likely has no ability to write so you receive a failure or your command is incorrect resulting in a 0 write or the process dies. (process death least likely) – Ryan Rentfro Dec 20 '20 at 19:26

2 Answers2

5

When you run the command manually, you are including sudo, but when you run the command in the crontab, you are not. Unless you are installing this as the root crontab, it will fail.

See the Manager Docker as a non-root user instructions here about how to setup Docker to run as non-root user.

Also, you are using the -it options, which expect an interactive terminal that is not available when run from crontab. You need to remove those arguments.

To get more details about the failure, you can redirect errors from the crontab command to a file for examination with 2>/path/to/file.

Putting it all together, your crontab entry will look something like:

0 24 * * * docker exec --user root lemp_mariadb mysqldump -uroot -pxxxxxxx iot  >/home/backup/backup_data.gz 2>/var/tmp/docker_msqldump_errors.log
Jason Peacock
  • 1,783
  • 11
  • 17
3

Jason Peacock answer is right But i would prefer to move the dump command into another shell script:

vim /home/backup/backup.sh

inside the backup.sh:

#!/bin/bash
echo 'Backing up db'
docker exec --user root lemp_mariadb /usr/bin/mysqldump -uroot -pxxxxxxx iot | gzip -9  > /home/backup/backup_data.sql.gz
chmod a+x /home/backup/backup.sh

Then in your crontab:

0 24 * * * /home/backup/backup.sh
abetobing
  • 159
  • 1
  • 2