因工作需求,在服务器的docker上部署的Mysql容器需要定时备份数据。于是在宿主机上写上了一个crontab,但是运行时没有报错,输出的文件大小为0。
备份脚本
1 | #!/bin/sh |
查看log
执行cat /var/log/cron
查看cron的执行状态1
2
3
4
5
6Jul 24 02:57:01 Server CROND[3646]: (root) MAIL (mailed 60 bytes of output but got status 0x004b#012)
Jul 24 02:58:01 Server CROND[3721]: (root) CMD (/root/Server/backup.sh)
Jul 24 02:58:01 Server CROND[3720]: (root) MAIL (mailed 60 bytes of output but got status 0x004b#012)
Jul 24 02:59:01 Server CROND[3795]: (root) CMD (/root/Server/backup.sh)
Jul 24 02:59:01 Server CROND[3794]: (root) MAIL (mailed 60 bytes of output but got status 0x004b#012)
Jul 24 03:00:01 Server CROND[3936]: (root) CMD (/root/Server/backup.sh)
问题排查及解决
从log可以看出脚本本身是没有问题的,于是把目标放定在docker exec
这段命令上。通过百度解决方法无果,于是打开梯子上谷歌搜寻结果。最后在stackoverflow上找到了解决方案。1
2
3
4
5
6
Your docker exec command says it needs "pseudo terminal and runs in interactive mode" (-it flags) while cron doesn't attach to any TTYs.
Try changing you docker exec command to this and see if that works?
docker exec mongodb mongodump -d meteor -o /dump/
意思就是说,docker exec -it
需要一个交互终端下运行,但是cron并不会附加到任何TTY。解决方法就是去掉-it
这个选项就可以了。最后备份脚本如下。1
2
3
4
5
6
7
8
9
10#!/bin/sh
BACKUP_DIR=/root/Server/Mysql/backup
TMP_DIR=/tmp/Mysql
docker exec dbc14c8c6660 mysqldump -uroot -pPASSWORD my_database > $TMP_DIR/my_database.sql
# Delete first row
# Mysql Warning
sed -i '1d' $TMP_DIR/my_database.sql
tar -zcf "$BACKUP_DIR/$(date '+%Y-%m-%d_%H%M%S')-my_database.tar.gz" -C $TMP_DIR my_database.sql
rm -f $TMP_DIR/my_database.sql