MariaDB

出自 Arch Linux 中文维基

MariaDB 是一個可靠的、高性能的、功能全面的數據庫,旨在為用戶提供長期免費、向下兼容能直接替代MySQL的數據庫服務。自2013年起,MariaDB就被Arch Linux當作官方默認的MySQL實現[1]

安裝[編輯 | 編輯原始碼]

Archlinux 選擇的 MySQL 默認實現 被稱為 MariaDB

安裝 mariadbmariadb-libs

提示:
  • 如果數據庫 (位於 /var/lib/mysql) 運行在 Btrfs 分區之上, 你應當在創建數據庫之前禁用 Copy-on-Write 特性。
  • 如果數據庫運行在 ZFS 分區之上, 你應該在創建數據庫之前參閱 ZFS#Databases

安裝 mariadb 軟件包之後,你必須在啟動 mariadb.service 之前運行下面這條命令:

# mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql

然後 enable 或者 start mariadb.service

提示:如果數據目錄使用的不是 /var/lib/mysql,需要在 /etc/my.cnf.d/server.cnf 文件的 [mysqld] 部分設置 datadir=<數據目錄>

配置[編輯 | 編輯原始碼]

啟動 mariadb 伺服器,並添加 root 維護帳號後,可以登錄伺服器進行進一步配置:

  1. mariadb -u root -p
注意: 默認密碼為空,直接敲回車鍵登錄

添加新用戶[編輯 | 編輯原始碼]

以下是創建一個密碼為'some_pass'的'monty'用戶的示例,並賦予 mydb 完全操作權限:

$ mariadb -u root -p
MariaDB> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
MariaDB> GRANT ALL PRIVILEGES ON mydb.* TO 'monty'@'localhost';
MariaDB> quit

配置文件[編輯 | 編輯原始碼]

MariaDB 會按照以下順序讀取配置文件 (根據 mysqld --help --verbose | tail -20 的輸出):

/etc/my.cnf /etc/my.cnf.d/ ~/.my.cnf

請根據需要的作用範圍(對系統, 對用戶...)修改對應的配置文件。 點擊 這裏 了解更多信息。

啟用自動補全[編輯 | 編輯原始碼]

注意: 啟用這項功能會增加客戶端啟動時間。

MySQL 默認禁用客戶端自動補全功能。要在整個系統中啟用它,編輯 /etc/my.cnf.d/mysql-clients.cnf,在mysql下 添加 auto-rehash。注意:不要將auto-rehash寫在mysqld下,下次客戶端啟動時就會啟用自動補全。

使用 UTF8MB4[編輯 | 編輯原始碼]

警告: Before changing the character set be sure to create a backup first.
注意:
  • The mariadb package already uses utf8mb4 as charset and utf8mb4_unicode_ci as collation. Users using the default (character) settings may want to skip this section.
  • UTF8MB4 is recommended over UTF-8 since it allows full Unicode support [2] [3].

Append the following values to the main configuration file located at /etc/my.cnf.d/my.cnf:

[client]
default-character-set = utf8mb4

[mariadb]
collation_server = utf8mb4_unicode_ci
character_set_server = utf8mb4

[mariadb-client]
default-character-set = utf8mb4

Restart mariadb.service to apply the changes. Changing the character set does not change existing table formats, only newly created tables, and the protocol interaction that fetches data.

See #Maintenance to optimize and check the database health.

使用內存作為臨時文件存放點[編輯 | 編輯原始碼]

MySQL 存儲臨時文件的目錄名是 tmpdir

創建一個臨時目錄:

# mkdir -pv /var/lib/mysqltmp
# chown mysql:mysql /var/lib/mysqltmp

通過命令找出 mysql 的id和gid:

$ id mysql
uid=27(mysql) gid=27(mysql) groups=27(mysql)

添加 tmpfs/etc/fstab 中。

 tmpfs   /var/lib/mysqltmp   tmpfs   rw,gid=27,uid=27,size=100M,mode=0750,noatime   0 0

將以下配置添加到 /etc/mysql/my.cnfmysqld 組下:

 tmpdir      = /var/lib/mysqltmp

Stop mariadb.service, mount /var/lib/mysqltmp/啟動 mariadb.service.

Time zone tables[編輯 | 編輯原始碼]

Although time zone tables are created during the installation, they are not automatically populated. They need to be populated if you are planning on using CONVERT_TZ() in SQL queries.

To populate the time zone tables with all the time zones:

$ mariadb-tzinfo-to-sql /usr/share/zoneinfo | mariadb -u root -p mysql

Optionally, you may populate the table with specific time zone files:

$ mariadb-tzinfo-to-sql timezone_file timezone_name | mariadb -u root -p mysql

Security[編輯 | 編輯原始碼]

Improve initial security[編輯 | 編輯原始碼]

The mariadb-secure-installation command will interactively guide you through a number of recommended security measures, such as removing anonymous accounts and removing the test database:

# mariadb-secure-installation
警告: After running this, please note that TCP port 3306 will still be open, but refusing connections with an error message. To prevent MySQL from listening on an external interface, see the #Listen only on the loopback address and #Enable access locally only via Unix sockets sections.

Listen only on the loopback address[編輯 | 編輯原始碼]

By default, MariaDB will listen on the 0.0.0.0 address, which includes all network interfaces. In order to restrict MariaDB to listen only to the loopback address, add the following line in /etc/my.cnf.d/server.cnf:

[mariadb]
bind-address = localhost

This will bind to both 127.0.0.1 and ::1, and enable MariaDB to receive connections both in IPv4 and IPv6.

Enable access locally only via Unix sockets[編輯 | 編輯原始碼]

By default, MariaDB is accessible via both Unix sockets and the network. If MariaDB is only needed for the localhost, you can improve security by not listening on TCP port 3306, and only listening on Unix sockets instead. To do this, add the following line in /etc/my.cnf.d/server.cnf:

[mariadb]
skip-networking

You will still be able to log in locally as before, but only using Unix sockets.

授權遠程訪問[編輯 | 編輯原始碼]

警告: This is not considered as best practice and may cause security issues. Consider using Secure Shell, VNC or VPN, if you want to maintain the MariaDB server from another host inside/outside your network.

To allow remote access to the MariaDB server, ensure that MariaDB has networking enabled and is listening on the appropriate interface.

Grant any MariaDB user remote access (example for root):

# mariadb -u root -p

Check current users with remote access privileged:

SELECT User, Host FROM mysql.user WHERE Host <> 'localhost';

Now grant remote access for your user (here root):

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%' IDENTIFIED BY 'my_optional_remote_password' WITH GRANT OPTION;

You can change the '%' wildcard to a specific host if you like. The password can be different from user's main password.

配置主目錄訪問[編輯 | 編輯原始碼]

注意: 出於安全考慮,systemd 的 .service 文件通過 ProtectHome=true 禁止 MariaDB 訪問 /home/root/run/user 目錄內的文件。datadir 必須要放在以上文件夾之外,並且由 mysql 用戶和用戶組 所有。 如果要改變這個設置,可以根據以下連結創建一個替代的 service 文件:[4]

維護[編輯 | 編輯原始碼]

升級[編輯 | 編輯原始碼]

mariadb大版本升級的時候(例如 mariadb-10.3.10-1 到 mariadb-10.9.4-1),最好更新一下數據庫:

# mariadb-upgrade -u root -p

要從 10.3.x 更新到 10.9.x:

  • 停止 10.3.x 伺服器
  • 更新軟件包
  • 啟動新服務並用執行新軟件包的 mariadb_upgrade

如果新服務未啟動,請參考 MariaDB 未啟動,無法執行 mariadb_upgrade。

備份[編輯 | 編輯原始碼]

Backup[編輯 | 編輯原始碼]

There are various tools and strategies to back up your databases.

If you are using the default InnoDB storage engine, a suggested way of backing up all your bases online while provisioning for point-in-time recovery (also known as "roll-forward", when you need to restore an old backup and replay the changes that happened since that backup) is to execute the following command:

$ mariadb-dump --single-transaction --flush-logs --events --routines --master-data=2 --all-databases -u root -p > all_databases.sql

This will prompt for MariaDB's root user's password, which was defined during database #Configuration.

Specifying the password on the command line is strongly discouraged, as it exposes it to discovery by other users through the use of ps aux or other techniques. Instead, the aforementioned command will prompt for the specified user's password, concealing it away.

Compression[編輯 | 編輯原始碼]

As SQL tables can get pretty large, it is recommended to pipe the output of the aforementioned command in a compression utility like gzip:

$ mariadb-dump --single-transaction --flush-logs --events --routines --master-data=2 --all-databases -u root -p | gzip > all_databases.sql.gz

Decompressing the backup thus created and reloading it in the server is achieved by doing:

$ zcat all_databases.sql.gz | mariadb -u root -p

This will recreate and repopulate all the databases previously backed up (see this or this).

Non-interactive[編輯 | 編輯原始碼]

If you want to setup non-interactive backup script for use in cron jobs or systemd timers, see option files and this illustration for mariadb-dump.

Basically you should add the following section to the relevant configuration file:

[mariadb-dump]
user=mysqluser
password=secret

Mentioning a user here is optional, but doing so will free you from having to mention it on the command line. If you want to set this for all tools, including mariadb-client, use the [client] group.

Example script[編輯 | 編輯原始碼]

The database can be dumped to a file for easy backup. The following shell script will do this for you, creating a db_backup.gz file in the same directory as the script, containing your database dump:

#!/bin/sh

THISDIR=$(dirname $(readlink -f "$0"))

mariadb-dump --single-transaction --flush-logs --events --routines --master-data=2 --all-databases \
 | gzip > $THISDIR/db_backup.gz
echo 'purge master logs before date_sub(now(), interval 7 day);' | mariadb

See also the official mariadb-dump page in the MariaDB manuals.

Holland Backup[編輯 | 編輯原始碼]

A python-based software package named Holland Backup is available in AUR to automate all of the backup work. It supports direct mysqldump, LVM snapshots to tar files (mysqllvm), LVM snapshots with mysqldump (mysqldump-lvm), and xtrabackup methods to extract the data. The Holland framework supports a multitude of options and is highly configurable to address almost any backup situation.

The main hollandAUR and holland-commonAUR packages provide the core framework; one of the sub-packages (holland-mysqldumpAUR, holland-mysqllvmAUR and/or holland-xtrabackupAUR must be installed for full operation. Example configurations for each method are in the /usr/share/doc/holland/examples/ directory and can be copied to /etc/holland/backupsets/, as well as using the holland mk-config command to generate a base configuration for a named provider.

故障排除[編輯 | 編輯原始碼]

執行 mysql_upgrade 後 MySQL 不能啟動[編輯 | 編輯原始碼]

試試安全模式下運行的 MySQL:

# mariadbd-safe --datadir=/var/lib/mysql/

然後再運行:

# mariadb-upgrade -u root -p

重置 root 密碼[編輯 | 編輯原始碼]

  1. 停止 mariadb.service.
  2. 用安全方式啟動服務:
    # mariadbd-safe --skip-grant-tables --skip-networking &
  3. 連接伺服器:
    # mariadb -u root
  4. 修改 root 密碼:
    MariaDB [mysql]> FLUSH PRIVILEGES;
    MariaDB [mysql]> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
    MariaDB [mysql]> exit
    
  5. 停掉 mariadbd* 進程:
    # kill $(cat /var/lib/mysql/$HOSTNAME.pid)
  6. 啟動 mariadb.service.

檢查並修復所有數據表[編輯 | 編輯原始碼]

檢查並自動修復所有數據庫中的所有表,查看更多

# mariadb-check -A --auto-repair -u root -p

優化所有數據表[編輯 | 編輯原始碼]

強制優化所有數據表,自動修復可能出現的數據表錯誤

# mariadb-check -A --auto-repair -f -o -u root -p

OS error 22 when running on ZFS[編輯 | 編輯原始碼]

如果您正在使用 ZFS 並且遇見了如下錯誤

InnoDB: Operating system error number 22 in a file operation.

那麼就需要修改 /etc/mysql/my.cnf 中的設置來禁用 aio_writes

[mariadb]
...
innodb_use_native_aio = 0

無法通過命令行登錄, 但是 phpmyadmin 正常工作[編輯 | 編輯原始碼]

當使用了超長 (>70-75) 的密碼後,這個問題有可能發生。 mariadb 的命令行不能在 readline 模式中處理那麼多的字符。 所以如果打算使用推薦的密碼輸入方式:

$ mariadb -u user -p
Password:

不妨考慮更換一個長度短一點的密碼。

注意: 您依然可以通過在命令行參數中指定密碼來登錄
$ mysql -u <user> -p"some-very-strong-password"
警告: 但這樣做很危險,因為您的密碼很可能會泄漏到某個地方,例如,日誌。只有當遇到緊急情況才能考慮這麼做,並且事後不要忘記更改密碼。

MySQL 日誌文件佔用太多空間[編輯 | 編輯原始碼]

默認情況下, mysqld 會在 /var/lib/mysql 下創建二進制日誌文件。這在某些場景下是很有用的。但是這些日誌文件也可能耗光您的硬盤空間。如果需要,您可以在 /etc/mysql/my.cnf 中註釋掉以下兩行來禁用日誌:

#log-bin=mysql-bin
#binlog_format=mixed

或者限制 logfile 的大小:

OpenRC fails to start MariaDB[編輯 | 編輯原始碼]

To use MariaDB with OpenRC you need to add the following lines to the [mariadb] section in the MySQL configuration file, located at /etc/my.cnf.d/my.cnf.

user = mysql
basedir = /usr
datadir = /var/lib/mysql
pid-file = /run/mysqld/mysql.pid

You should now be able to start MariaDB using:

# rc-service mysql start

Specified key was too long[編輯 | 編輯原始碼]

See #Increase character limit.

Changed limits warning on max_open_files/table_open_cache[編輯 | 編輯原始碼]

Increase the number of file descriptors by creating a systemd drop-in, e.g.:

/etc/systemd/system/mariadb.service.d/limit_nofile.conf
[Service]
LimitNOFILE=8192

10.4 to 10.5 upgrade crash: "InnoDB: Upgrade after a crash is not supported. The redo log was created with MariaDB 10.4.x"[編輯 | 編輯原始碼]

Before MariaDB 10.5, redo log was unnecessarily split into multiple files.[5]

Do NOT ever remove the old binary logs /var/lib/mysql/ib_logfile* out of the way.

To resolve this, install MariaDB 10.4. Start it and let it undergo a clean shutdown. After that happens you can upgrade to 10.5 again. Same applies if another version of MariaDB was specified.

Table 'mysql.xxx' does not exist in engine[編輯 | 編輯原始碼]

Symptom: When running mariadb-upgrade or mariadb-check, it return one or more error like these:

Table 'mysql.xxx' does not exist in engine

Where "xxx" usually is the system table inside the mysql database.

Steps to fix this,

  1. Create backup directory outside of MariaDB ${DATADIR}</nowiki>, for example in $HOME/mariadb_backup.
  2. Copy the offending files from ${DATADIR}/mysql/xxx.{frm,ibd}</nowiki> to backup directory. The xxx.ibd may not exist.
  3. Drop the tables with DROP TABLE mysql.xxx on the mariadb prompt.
  4. Run the mariadb-check. On success, the file xxx.frm and xxx.ibd should be created again.
  5. Re-run mariadb-upgrade if necessary. You may need the --force option.
expire_logs_days = 10
max_binlog_size  = 100M

另外,您也可以執行以下命令來清除 /var/lib/mysql 裡的一些日誌文件來釋放硬盤空間:

#mysql -u root -p"PASSWORD" -e "PURGE BINARY LOGS TO 'mysql-bin.0000xx';"

更多資源[編輯 | 編輯原始碼]