Ubuntu18中path中自带mysql5.7,可以通过apt直接安装。
本文详细介绍安装方式以及对数据库进行定时备份。
sudo apt update
sudo apt install mysql-server
sudo apt install mysql-client
sudo apt install libmysqlclient-dev
安装完成后检查mysql版本
mysql --version
显示如下:
mysql Ver 14.14 Distrib 5.7.42, for Linux (x86_64) using EditLine wrapper
mysql的配置文件默认在/etc/mysql/mysql.conf.d/mysqld.cnf
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
把bind-address中的127.0.0.1改为0.0.0.0,即外部设备可以通过IP访问数据库。
修改端口等配置也在此文件中。
sudo vim /etc/mysql/debian.cnf
如下:
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host = localhost
user = debian-sys-maint
password = FXp25ENG3Ig9XXX
socket = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host = localhost
user = debian-sys-maint
password = FXp25ENG3Ig9XXX
socket = /var/run/mysqld/mysqld.sock
复制出来user和password
使用复制出来的user和password登录mysql
mysql -u debian-sys-maint -pFXp25ENG3Ig9XXX
修改root密码并允许外部ip访问
use mysql;
update mysql.user set authentication_string=password('yourpassword') where user='root' and Host ='localhost';
update user set plugin="mysql_native_password";
update user set host="%" where user="root";
flush privileges;
sudo systemctl restart mysql
sudo systemctl start mysql
sudo systemctl stop mysql
sudo systemctl status mysql
我想把mysql数据库备份在/usr/local/mysql5.7/backup/下
mysqldump -uroot -pyourpassword dbname > /usr/local/mysql5.7/backup/1.sql
如果出现bash: /usr/local/mysql5.7/backup/1.sql: 权限不够
执行增加权限
sudochmod -R 777 mysql5.7/
在/usr/local/mysql5.7/backup/下新建db_backup.sh,放入以下内容:
#!/bin/bash
DATE=`date +%Y%m%d%H%M` #every minute
DATABASE=dbname #database name
DB_USERNAME=root #database username
DB_PASSWORD=yourpassword #database password
BACKUP_PATH=/usr/local/mysql5.7/backup #backup path
#backup command
mysqldump -u$DB_USERNAME -p$DB_PASSWORD $DATABASE > ${BACKUP_PATH}\/${DATABASE}_${DATE}.sql
#just backup the latest 7 days
find ${BACKUP_PATH} -mtime +7 -name "${DATABASE}_*.sql" -exec rm -f {} \;
设置执行权限:
sudo chmod +x db_backup.sh
执行./db_backup.sh即可备份成功
使用cron做定时任务。
添加定时任务:
sudo vim /etc/crontab
添加:
25 10 * * * root /usr/local/mysql5.7/backup/db_backup.sh
以上内容表示每天10点25分使用root用户执行文件
重启cron服务
sudo service cron restart