MariaDB介绍和安装

MariaDB介绍和安装

1.MariaDB介绍

MariaDB是一个开源的关系型数据库管理系统(DBMS),它是MySQL数据库的一个分支。它由MySQL的创始人之一Michael Widenius在Oracle收购Sun Microsystems后,对MySQL的未来发展感到担忧而创建的。

MariaDB的目标是提供一个兼容MySQL的数据库系统,并且在功能和性能上进行改进。它保留了与MySQL相同的API和命令语法,因此现有的MySQL应用程序可以无缝地迁移到MariaDB上。

MariaDB的特点包括:

  1. 开源性:MariaDB是一个开源项目,任何人都可以免费使用、修改和分发它。
  2. 兼容性:MariaDB与MySQL高度兼容,可以无缝地替代MySQL。大多数MySQL的客户端和驱动程序都可以与MariaDB一起使用。
  3. 性能优化:MariaDB针对性能进行了一些改进,包括优化查询执行计划、改进索引算法等,以提供更好的性能。
  4. 新功能:MariaDB在功能上进行了一些扩展和改进,包括支持新的存储引擎(如XtraDB和Aria)、更好的复制和高可用性功能、更好的安全性等。
  5. 社区支持:MariaDB有一个活跃的社区,提供了广泛的文档、教程和支持资源。社区成员可以共同开发和改进MariaDB,使其不断发展和完善。

总体而言,MariaDB是一个可替代MySQL的开源关系型数据库管理系统,它提供了更好的性能、更多的功能和广泛的社区支持。许多组织和开发者选择使用MariaDB来构建他们的应用程序和服务。

2.MariaDB安装

2.1 主机初始化

2.1.1 设置网卡名和ip地址

Rocky 9和CentOS Stream 9:

sql 复制代码
# Rocky 9和CentOS Stream 9默认支持修改网卡名。
[root@rocky9 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=keyfile,ifcfg-rh
# 因为网卡命名方式默认是keyfile,默认不支持修改网卡名,既然官方已经默认是keyfile那这里就不去更改网卡名了。
​
[root@rocky9 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
​
[root@rocky9 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.9/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli con up ${ETHNAME}
# 172.31.0.9/21中172.31.0.9是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
​
[root@rocky9 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::51ca:fd5d:3552:677d/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 可以看到ip地址已修改。

Rocky 8、CentOS Stream 8和CentOS 7:

perl 复制代码
# Rocky 8、CentOS Stream 8和CentOS 7支持修改网卡名。
[root@rocky8 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=ifcfg-rh
# 因为网卡命名方式默认是ifcfg-rh,支持修改网卡名。
​
# 修改网卡名称配置文件
[root@rocky8 ~]# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0 biosdevname=0"@' /etc/default/grub
[root@rocky8 ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
done
​
# 修改网卡文件名
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky8 ~]# mv /etc/sysconfig/network-scripts/ifcfg-${ETHNAME} /etc/sysconfig/network-scripts/ifcfg-eth0
​
[root@rocky8 ~]# shutdown -r now
​
​
[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION         
eth0    ethernet  connected  Wired connection 1 
lo      loopback  unmanaged  --
# 可以看到CONNECTION的名字是Wired connection 1,要改名才可以下面设置。
​
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
​
[root@rocky8 ~]# nmcli connection modify "Wired connection 1" con-name ${ETHNAME}
[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION 
eth0    ethernet  connected  eth0       
lo      loopback  unmanaged  --  
​
# 修改ip地址
[root@rocky8 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.8/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli dev up eth0
# 172.31.0.8/21中172.31.0.8是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
​
[root@rocky8 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:6f:65:d3 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 172.31.0.8/21 brd 172.31.7.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::e9c9:aa93:4a58:2cc2/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

Ubuntu:

yaml 复制代码
# Ubuntu先启用root用户,并设置密码
raymond@ubuntu2204:~$ cat set_root_login.sh 
#!/bin/bash
​
read -p "请输入密码: " PASSWORD
echo ${PASSWORD} |sudo -S sed -ri 's@#(PermitRootLogin )prohibit-password@\1yes@' /etc/ssh/sshd_config
sudo systemctl restart sshd
sudo -S passwd root <<-EOF
${PASSWORD}
${PASSWORD}
EOF
​
raymond@ubuntu2204:~$ bash set_root_login.sh 
请输入密码: 123456
[sudo] password for raymond: New password: Retype new password: passwd: password updated successfully
​
raymond@ubuntu2204:~$ rm -rf set_root_login.sh
​
# 使用root登陆,修改网卡名
root@ubuntu2204:~# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@net.ifnames=0 biosdevname=0"@' /etc/default/grub
root@ubuntu2204:~# grub-mkconfig -o /boot/grub/grub.cfg
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.15.0-88-generic
Found initrd image: /boot/initrd.img-5.15.0-88-generic
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
done
​
# Ubuntu 20.04设置ip地址
root@ubuntu2004:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.20/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu20.04网卡配置文件是00-installer-config.yaml;172.31.0.20/21中172.31.0.20是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
​
# Ubuntu 18.04设置ip地址
root@ubuntu1804:~# cat > /etc/netplan/01-netcfg.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.18/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu18.04网卡配置文件是01-netcfg.yaml;172.31.0.18/21中172.31.0.18是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
​
root@ubuntu2004:~# shutdown -r now
​
root@ubuntu2004:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e5:98:6f brd ff:ff:ff:ff:ff:ff
    inet 172.31.0.20/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee5:986f/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。
​
# Ubuntu 22.04设置ip地址
root@ubuntu2204:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.22/21]
      routes:
        - to: default
          via: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu 22.04网卡配置文件是00-installer-config.yaml;172.31.0.22/21中172.31.0.22是ip地址,21是子网位数;172.31.0.2是网关地址,Ubuntu 22.04设置网关地址的方法发生了改变,参考上面的方法;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
​
root@ubuntu2204:~# shutdown -r now
​
# 重启后使用新设置的ip登陆
root@ubuntu2204:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:a7:be:f2 brd ff:ff:ff:ff:ff:ff
    altname enp2s1
    altname ens33
    inet 172.31.0.22/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fea7:bef2/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

2.1.2 配置镜像源

Rocky 8和9:

bash 复制代码
MIRROR=mirrors.sjtug.sjtu.edu.cn
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://'${MIRROR}'/rocky|g' /etc/yum.repos.d/[Rr]ocky*.repo
​
dnf clean all && dnf makecache

CentOS Stream 9:

perl 复制代码
cat update_mirror.pl
#!/usr/bin/perl
​
use strict;
use warnings;
use autodie;
​
# 要修改镜像源,请去修改url变量!
my $url = 'mirrors.aliyun.com';
my $mirrors = "https://$url/centos-stream";
​
if (@ARGV < 1) {
    die "Usage: $0 <filename1> <filename2> ...\n";
}
​
while (my $filename = shift @ARGV) {
    my $backup_filename = $filename . '.bak';
    rename $filename, $backup_filename;
​
    open my $input, "<", $backup_filename;
    open my $output, ">", $filename;
​
    while (<$input>) {
        s/^metalink/# metalink/;
​
        if (m/^name/) {
            my (undef, $repo, $arch) = split /-/;
            $repo =~ s/^\s+|\s+$//g;
            ($arch = defined $arch ? lc($arch) : '') =~ s/^\s+|\s+$//g;
​
            if ($repo =~ /^Extras/) {
                $_ .= "baseurl=${mirrors}/SIGs/$releasever-stream/extras" . ($arch eq 'source' ? "/${arch}/" : "/$basearch/") . "extras-common\n";
            } else {
                $_ .= "baseurl=${mirrors}/$releasever-stream/$repo" . ($arch eq 'source' ? "/" : "/$basearch/") . ($arch ne '' ? "${arch}/tree/" : "os") . "\n";
            }
        }
​
        print $output $_;
    }
}
​
rpm -q perl &> /dev/null || { echo -e "\033[01;31m "安装perl工具,请稍等..."\033[0m";yum -y install perl ; }
​
perl ./update_mirror.pl /etc/yum.repos.d/centos*.repo
​
dnf clean all && dnf makecache

CentOS Stream 8:

bash 复制代码
MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/$contentdir|baseurl=https://'${MIRROR}'/centos|g' /etc/yum.repos.d/CentOS-*.repo
​
dnf clean all && dnf makecache

CentOS 7:

bash 复制代码
MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://'${MIRROR}'|g' /etc/yum.repos.d/CentOS-*.repo
​
yum clean all && yum makecache

Ubuntu 22.04和20.04:

bash 复制代码
MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`
​
sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list
​
apt update

Ubuntu 18.04:

bash 复制代码
MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

SECURITY_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu $(lsb_release -cs)-security main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${SECURITY_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

apt update

2.1.3 关闭防火墙

bash 复制代码
# Rocky和CentOS
systemctl disable --now firewalld

# CentOS 7
systemctl disable --now NetworkManager

# Ubuntu
systemctl disable --now ufw

2.1.4 禁用SELinux

less 复制代码
#CentOS
setenforce 0
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config

#Ubuntu
Ubuntu没有安装SELinux,不用设置

2.1.5 设置时区

bash 复制代码
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' >/etc/timezone

#Ubuntu还要设置下面内容
cat >> /etc/default/locale <<-EOF
LC_TIME=en_DK.UTF-8
EOF

2.2 包安装

2.2.1 Rocky和CentOS 安装 MariaDB

yaml 复制代码
[root@rocky9 ~]# yum list mariadb-server --showduplicates
Last metadata expiration check: 0:04:58 ago on Sun 25 Feb 2024 09:06:43 PM CST.
Available Packages
mariadb-server.x86_64                                  3:10.5.22-1.el9_2                                   appstrea

[root@rocky9 ~]# yum -y install mariadb-server

[root@rocky9 ~]# systemctl enable --now mariadb

[root@rocky9 ~]# ls /var/lib/mysql
aria_log.00000001  ib_buffer_pool  ib_logfile0  multi-master.info  mysql.sock          performance_schema
aria_log_control   ibdata1         ibtmp1       mysql              mysql_upgrade_info

[root@rocky9 ~]# mysql -V
mysql  Ver 15.1 Distrib 10.5.22-MariaDB, for Linux (x86_64) using  EditLine wrapper

[root@rocky9 ~]# systemctl status mariadb
● mariadb.service - MariaDB 10.5 database server
     Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; preset: disabled)
     Active: active (running) since Sun 2024-02-25 21:16:07 CST; 1min 6s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 12752 ExecStartPre=/usr/libexec/mariadb-check-socket (code=exited, status=0/SUCCESS)
    Process: 12774 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir mariadb.service (code=exited, status=0/SUCCESS)
    Process: 12873 ExecStartPost=/usr/libexec/mariadb-check-upgrade (code=exited, status=0/SUCCESS)
   Main PID: 12857 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 8 (limit: 10840)
     Memory: 70.2M
        CPU: 393ms
     CGroup: /system.slice/mariadb.service
             └─12857 /usr/libexec/mariadbd --basedir=/usr

Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: The second is mysql@localhost, it has no password either, but
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: you need to be the system 'mysql' user to connect.
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: After connecting you can set the password, if you would need >
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: able to connect as any of these users with a password and wit>
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: See the MariaDB Knowledgebase at https://mariadb.com/kb
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: Please report any problems at https://mariadb.org/jira
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: The latest information about MariaDB is available at https://>
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: Consider joining MariaDB's strong and vibrant community:
Feb 25 21:16:06 rocky9 mariadb-prepare-db-dir[12813]: https://mariadb.org/get-involved/
Feb 25 21:16:07 rocky9 systemd[1]: Started MariaDB 10.5 database server.

[root@rocky9 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status
--------------
mysql  Ver 15.1 Distrib 10.5.22-MariaDB, for Linux (x86_64) using  EditLine wrapper

Connection id:		3
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		10.5.22-MariaDB MariaDB Server
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
UNIX socket:		/var/lib/mysql/mysql.sock
Uptime:			1 min 36 sec

Threads: 1  Questions: 4  Slow queries: 0  Opens: 17  Open tables: 10  Queries per second avg: 0.041
--------------

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.000 sec)

MariaDB [(none)]> exit
Bye

2.2.2 Ubuntu 安装 MariaDB

yaml 复制代码
root@ubuntu2204:~# apt-cache madison mariadb-server
mariadb-server | 1:10.6.16-0ubuntu0.22.04.1 | https://mirrors.aliyun.com/ubuntu jammy-updates/universe amd64 Packages
mariadb-server | 1:10.6.16-0ubuntu0.22.04.1 | https://mirrors.aliyun.com/ubuntu jammy-security/universe amd64 Packages
mariadb-server | 1:10.6.7-2ubuntu1 | https://mirrors.aliyun.com/ubuntu jammy/universe amd64 Packages

root@ubuntu2204:~# apt -y install mariadb-server

root@ubuntu2204:~# systemctl enable --now mariadb

root@ubuntu2204:~# ls /var/lib/mysql
aria_log.00000001  ddl_recovery.log  ib_buffer_pool  ibdata1  multi-master.info  mysql_upgrade_info  sys
aria_log_control   debian-10.6.flag  ib_logfile0     ibtmp1   mysql              performance_schema

root@ubuntu2204:~# mysql -V
mysql  Ver 15.1 Distrib 10.6.16-MariaDB, for debian-linux-gnu (x86_64) using  EditLine wrapper

root@ubuntu2204:~# systemctl status mariadb
● mariadb.service - MariaDB 10.6.16 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2024-02-25 21:24:13 CST; 1min 16s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
   Main PID: 2178 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 8 (limit: 2178)
     Memory: 61.1M
        CPU: 389ms
     CGroup: /system.slice/mariadb.service
             └─2178 /usr/sbin/mariadbd

Feb 25 21:24:13 ubuntu2204 mariadbd[2178]: Version: '10.6.16-MariaDB-0ubuntu0.22.04.1'  socket: '/run/mysqld/mysqld>
Feb 25 21:24:13 ubuntu2204 systemd[1]: Started MariaDB 10.6.16 database server.
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2192]: Upgrading MySQL tables if necessary.
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2195]: Looking for 'mariadb' as: /usr/bin/mariadb
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2195]: Looking for 'mariadb-check' as: /usr/bin/mariadb-check
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2195]: This installation of MariaDB is already upgraded to 10.6.>
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2195]: There is no need to run mysql_upgrade again for 10.6.16-M>
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2195]: You can use --force if you still want to run mysql_upgrade
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2205]: Checking for insecure root accounts.
Feb 25 21:24:13 ubuntu2204 /etc/mysql/debian-start[2209]: Triggering myisam-recover for all MyISAM tables and aria->

root@ubuntu2204:~# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 31
Server version: 10.6.16-MariaDB-0ubuntu0.22.04.1 Ubuntu 22.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status
--------------
mysql  Ver 15.1 Distrib 10.6.16-MariaDB, for debian-linux-gnu (x86_64) using  EditLine wrapper

Connection id:		31
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		10.6.16-MariaDB-0ubuntu0.22.04.1 Ubuntu 22.04
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	utf8mb4
Db     characterset:	utf8mb4
Client characterset:	utf8mb3
Conn.  characterset:	utf8mb3
UNIX socket:		/run/mysqld/mysqld.sock
Uptime:			2 min 16 sec

Threads: 1  Questions: 61  Slow queries: 0  Opens: 33  Open tables: 26  Queries per second avg: 0.448
--------------

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.001 sec)

MariaDB [(none)]> exit
Bye

2.3 源码安装

建议:内存6G以上,否则编译时可能会出错,这里设置的4C8G。

2.3.1 安装相关依赖包

perl 复制代码
# CentOS 7
yum -y install bison bison-devel zlib-devel libcurl-devel libarchive-devel boost-devel gcc gcc-c++ ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel pcre2

# Rocky 8/9和CentOS 8/9
yum -y install bison zlib-devel libcurl-devel libarchive boost-devel gcc gcc-c++ cmake ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel

# ubuntu
apt update

# 安装帮助:https://mariadb.com/kb/en/building-mariadb-on-ubuntu/
# 如果您使用的是基于 Linux 的操作系统 Ubuntu 或其任何衍生版本,并且想从源代码编译 MariaDB,您可以使用您感兴趣的版本的 MariaDB 源存储库。
# 在开始之前,安装 software-properties-common、devscripts 和 equivs 包。
apt -y install software-properties-common devscripts equivs

# 安装构建依赖项
# MariaDB 需要许多包才能从源代码编译。幸运的是,您可以使用 MariaDB 存储库来检索所需版本的必要代码。使用存储库配置工具来确定如何为您的 Ubuntu 版本、要安装的 MariaDB 版本以及要使用的镜像设置 MariaDB 存储库。
# 添加存储库的身份验证密钥
apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8

# 添加存储库
add-apt-repository --update --yes --enable-source 'deb [arch=amd64] http://nyc2.mirrors.digitalocean.com/mariadb/repo/11.3/ubuntu '$(lsb_release -sc)' main'

# 设置存储库后,您可以使用 apt-get 检索构建依赖项。Ubuntu 提供的 MariaDB 包和 MariaDB 存储库提供的包具有相同的基本名称 mariadb-server。您需要指定要检索的特定版本。
apt update
apt -y build-dep mariadb

2.3.2 做准备用户和数据目录

bash 复制代码
useradd -r -s /sbin/nologin -d /data/mysql mysql

2.3.3 准备数据库目录

bash 复制代码
mkdir -p /data/mysql
chown mysql.mysql /data/mysql

2.3.4 源码编译安装

编译安装说明

利用cmake编译,而利用传统方法,cmake的重要特性之一是其独立于源码(out-of-source)的编译功能,即编译工作可以在另一个指定的目录中而非源码目录中进行,这可以保证源码目录不受任何一次编译的影响,因此在同一个源码树上可以进行多次不同的编译,如针对于不同平台编译

编译选项:dev.mysql.com/doc/refman/...

2.3.4.1 下载并解压缩源码包

MariaDB源码包下载,去"mariadb.org//"网站下载,选择"Download"。

在弹出的网页,选择"MariaDB Server Version为:MariaDB Server 11.3.2",选择"Operating System为:Source",然后选下面的"Download"。

bash 复制代码
cd /usr/local/src

# 官方下载地址
wget https://mirrors.xtom.com.hk/mariadb//mariadb-11.3.2/source/mariadb-11.3.2.tar.gz

# 清华下载地址
wget https://mirrors.tuna.tsinghua.edu.cn/mariadb/mariadb-11.3.2/source/mariadb-11.3.2.tar.gz

tar xvf mariadb-11.3.2.tar.gz

2.3.4.2 源码编译安装mariadb

ini 复制代码
cd mariadb-11.3.2

cmake . \
-DCMAKE_INSTALL_PREFIX=/apps/mysql \
-DMYSQL_DATADIR=/data/mysql/ \
-DSYSCONFDIR=/etc/ \
-DMYSQL_USER=mysql \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITHOUT_MROONGA_STORAGE_ENGINE=1 \
-DWITH_DEBUG=0 \
-DWITH_READLINE=1 \
-DWITH_SSL=system \
-DWITH_ZLIB=system \
-DWITH_LIBWRAP=0 \
-DENABLED_LOCAL_INFILE=1 \
-DMYSQL_UNIX_ADDR=/data/mysql/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci

# 编译完成后会有类似如下的输出
-- The following OPTIONAL packages have not been found:

 * Git
 * Java (required version >= 1.6)
   Required for the CONNECT_JDBC feature
 * JNI
   Required for the CONNECT_JDBC feature
 * PMEM
 * Judy
   Required for the OQGraph storage engine
 * GSSAPI
 * BZip2
 * LZ4 (required version >= 1.6)
 * LZO
 * Snappy

-- Configuring done
-- Generating done
-- Build files have been written to: /usr/local/src/mariadb-11.3.2

make -j 4 && make install

提示:如果出错,执行rm -f CMakeCache.txt

CentOS 7报错处理

ini 复制代码
CMake Error at CMakeLists.txt:106 (CMAKE_MINIMUM_REQUIRED):
  CMake 3.1 or higher is required.  You are running version 2.8.12.2


-- Configuring incomplete, errors occurred!
# CentOS 7如果使用镜像源的cmake会提示CMake版本低,需要安装CMake 3.1或更高版本。

# 去"https://cmake.org/download/"网址下载cmake源码包

cd ..
wget https://github.com/Kitware/CMake/releases/download/v3.29.0-rc1/cmake-3.29.0-rc1.tar.gz

tar xvf cmake-3.29.0-rc1.tar.gz
cd cmake-3.29.0-rc1

./configure

make -j 4 && make install

/usr/local/bin/cmake --version
cmake version 3.29.0-rc1

CMake suite maintained and supported by Kitware (kitware.com/cmake).

ln -s /usr/local/bin/cmake /usr/bin/

cd ../mariadb-11.3.2/
cmake . \
-DCMAKE_INSTALL_PREFIX=/apps/mysql \
-DMYSQL_DATADIR=/data/mysql/ \
-DSYSCONFDIR=/etc/ \
-DMYSQL_USER=mysql \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITHOUT_MROONGA_STORAGE_ENGINE=1 \
-DWITH_DEBUG=0 \
-DWITH_READLINE=1 \
-DWITH_SSL=system \
-DWITH_ZLIB=system \
-DWITH_LIBWRAP=0 \
-DENABLED_LOCAL_INFILE=1 \
-DMYSQL_UNIX_ADDR=/data/mysql/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci

make -j 4 && make install

2.3.5 准备环境变量

bash 复制代码
echo 'PATH=/apps/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
. /etc/profile.d/mysql.sh

chown -R mysql.mysql /apps/mysql/

2.3.6 生成数据库文件

bash 复制代码
#这里必须先要进入/apps/mysql/目录,在执行下面命令
cd /apps/mysql/
./scripts/mysql_install_db --datadir=/data/mysql/ --user=mysql

2.3.7 准备配置文件

ini 复制代码
cat > /etc/my.cnf <<EOF
[mysqld]
basedir=/apps/mysql/
datadir=/data/mysql
port=3306
socket=/data/mysql/mysql.sock 
pid-file=/data/mysql/mysql.pid 

[mysqld_safe]
log-error=/data/mysql/mysql.log 

[mysql]
default-character-set=utf8mb4

[client]
port=3306
socket=/data/mysql/mysql.sock
default-character-set=utf8mb4
EOF

2.3.8 准备启动脚本并启动服务

ini 复制代码
# Rocky 9和CentOS 9默认没有chkconfig包,需要安装
yum -y install chkconfig

cp /apps/mysql/support-files/mysql.server /etc/init.d/mysqld

# Rocky和CentOS
chkconfig --add mysqld

# Ubuntu
update-rc.d -f mysqld defaults

cat > /lib/systemd/system/mysqld.service <<-EOF
[Unit]
Description=mysql database server
After=network.target

[Service]
Type=notify
PrivateNetwork=false
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
SuccessExitStatus=5 6
ExecStart=/etc/init.d/mysqld start
ExecStop=/etc/init.d//mysqld stop
ExecReload=/etc/init.d/mysqld reload

[Install]
WantedBy=multi-user.target
Alias=mysqld.service
EOF

systemctl daemon-reload && systemctl enable --now mysqld

2.3.9 安全初始化

vbnet 复制代码
mysql
mysql: Deprecated program name. It will be removed in a future release, use '/apps/mysql/bin/mariadb' instead
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 11.3.2-MariaDB Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.001 sec)
# MariaDB默认有test数据库

MariaDB [(none)]> select user,host from mysql.user;
+-------------+-----------+
| User        | Host      |
+-------------+-----------+
| PUBLIC      |           |
|             | localhost | # 匿名用户
| mariadb.sys | localhost |
| mysql       | localhost | 
| root        | localhost |
|             | rocky9-2  | # 远程登录用户
+-------------+-----------+
6 rows in set (0.002 sec)

MariaDB [(none)]> exit
Bye
# MariaDB默认有匿名用户和远程登录用户,需要安全初始化

mysql_secure_installation
/apps/mysql/bin/mysql_secure_installation: Deprecated program name. It will be removed in a future release, use 'mariadb-secure-installation' instead

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): # 输入 root 的当前密码(不输入),直接敲回车
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] y # 输入y,切换到 unix_socket 身份验证
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] y # 输入y,开始设置root密码
New password: # 连续输入两次密码(要记住密码啊) 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y # 输入y,移除匿名账户
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y # 输入y,禁止 root 远程登录
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y # 输入y,移除测试库
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y # 输入y,重新加载权限表
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

2.3.10 登录测试

sql 复制代码
mysql -uroot -p123456
mysql: Deprecated program name. It will be removed in a future release, use '/apps/mysql/bin/mariadb' instead
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 15
Server version: 11.3.2-MariaDB Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status
--------------
mysql from 11.3.2-MariaDB, client 15.2 for Linux (x86_64) using readline 5.1

Connection id:		15
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		11.3.2-MariaDB Source distribution
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	utf8mb3
Db     characterset:	utf8mb3
Client characterset:	utf8mb4
Conn.  characterset:	utf8mb4
UNIX socket:		/data/mysql/mysql.sock
Uptime:			11 min 45 sec

Threads: 1  Questions: 31  Slow queries: 0  Opens: 21  Open tables: 14  Queries per second avg: 0.043
--------------

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.000 sec)
# 可以看到已经没有test数据库了

MariaDB [(none)]> select user,host from mysql.user;
+-------------+-----------+
| User        | Host      |
+-------------+-----------+
| PUBLIC      |           |
| mariadb.sys | localhost |
| mysql       | localhost |
| root        | localhost |
+-------------+-----------+
4 rows in set (0.001 sec)
# 可以看到已经没有匿名用户和远程登录用户了

MariaDB [(none)]> exit
Bye

2.3.11 一键安装MySQL源码编译的脚本

Shell脚本源码地址:

Gitee:gitee.com/raymond9/sh...

Github:github.com/raymond9999...

可以去上面的Gitee或Github代码仓库拉取脚本。

bash 复制代码
[root@rocky9-2 ~]# cat install_mariadb_source_v2.sh 
root@ubuntu2004:~# cat install_mariadb_source_v2.sh 
#!/bin/bash
#
#******************************************************************************************************************
#Author:        Raymond
#QQ:            88563128
#Date:          2024-02-25
#FileName:      install_mariadb_source_v2.sh
#URL:           raymond.blog.csdn.net
#Description:   install_mariadb_source for CentOS 7 & CentOS Stream 8/9 & Ubuntu 18.04/20.04/22.04 & Rocky 8/9
#Copyright (C): 2024 All rights reserved
#******************************************************************************************************************
SRC_DIR=/usr/local/src
INSTALL_DIR=/apps/mysql
DATA_DIR=/data/mysql
COLOR="echo -e \033[01;31m"
END='\033[0m'

MARIADB_URL='https://mirrors.tuna.tsinghua.edu.cn/mariadb/mariadb-11.3.2/source/'
MARIADB_FILE='mariadb-11.3.2.tar.gz'
MARIADB_VERSION='11.3'

#cmake下载地址:"https://github.com/Kitware/CMake/releases/download/v3.29.0-rc1/cmake-3.29.0-rc1.tar.gz",请提前下载。
CMAKE_FILE=cmake-3.29.0-rc1.tar.gz

CPUS=`lscpu |awk '/^CPU(s)/{print $2}'`
MYSQL_ROOT_PASSWORD=123456

os(){
    OS_ID=`sed -rn '/^NAME=/s@.*="([[:alpha:]]+).*"$@\1@p' /etc/os-release`
    OS_RELEASE_VERSION=`sed -rn '/^VERSION_ID=/s@.*="?([0-9]+).?.*"?@\1@p' /etc/os-release`
}

check_file(){
    cd  ${SRC_DIR}
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        rpm -q wget &> /dev/null || { ${COLOR}"安装wget工具,请稍等..."${END};yum -y install wget &> /dev/null; }
    fi
    if [ ! -e ${MARIADB_FILE} ];then
        ${COLOR}"缺少${MARIADB_FILE}文件"${END}
        ${COLOR}'开始下载MariaDB源码包'${END}
        wget ${MARIADB_URL}${MARIADB_FILE} || { ${COLOR}"MariaDB源码包下载失败"${END}; exit; }
    else
        ${COLOR}"${MARIADB_FILE}文件已准备好"${END}
    fi
    if [ ${OS_ID} == "CentOS" -a ${OS_RELEASE_VERSION} == 7 ];then
        if [ ! -e ${CMAKE_FILE} ];then
            ${COLOR}"缺少${CMAKE_FILE}文件,请把文件放到${SRC_DIR}目录下"${END}
        else
            ${COLOR}"${CMAKE_FILE}相关文件已准备好"${END}
        fi
    fi
}

install_mysql(){
    [ -d ${INSTALL_DIR} ] && { ${COLOR}"MariaDB数据库已存在,安装失败"${END};exit; }
    ${COLOR}"开始安装MariaDB数据库..."${END}
    ${COLOR}'开始安装MariaDB依赖包'${END}
    if [ ${OS_RELEASE_VERSION} == 8 -o ${OS_RELEASE_VERSION} == 9 ] &> /dev/null;then
        yum -y install bison zlib-devel libcurl-devel libarchive boost-devel gcc gcc-c++ cmake ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel &> /dev/null
    elif [[ ${OS_RELEASE_VERSION} == 7 ]] &> /dev/null;then
        yum -y install bison bison-devel zlib-devel libcurl-devel libarchive-devel boost-devel gcc gcc-c++ ncurses-devel gnutls-devel libxml2-devel openssl-devel libevent-devel libaio-devel pcre2 pcre2-devel &> /dev/null
    else
        apt update &> /dev/null;apt -y install software-properties-common devscripts equivs &> /dev/null
        apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8 &> /dev/null
        add-apt-repository --update --yes --enable-source 'deb [arch=amd64] http://nyc2.mirrors.digitalocean.com/mariadb/repo/'${MARIADB_VERSION}'/ubuntu '$(lsb_release -sc)' main' &> /dev/null
        apt update &> /dev/null
		apt -y build-dep mariadb &> /dev/null
    fi

    id mysql &> /dev/null || { useradd -r -s /sbin/nologin -d ${DATA_DIR} mysql ; ${COLOR}"创建mysql用户"${END}; }
    [ -d ${INSTALL_DIR} ] || mkdir -p ${DATA_DIR} &> /dev/null
    chown -R mysql.mysql ${DATA_DIR}

    if [ ${OS_ID} == "CentOS" -a ${OS_RELEASE_VERSION} == 7 ];then
        tar xf ${CMAKE_FILE}
        CMAKE_DIR=`echo ${CMAKE_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
        cd ${CMAKE_DIR}
        ./configure
        make -j ${CPUS} && make install
        ln -s /usr/local/bin/cmake /usr/bin/
    fi

    cd  ${SRC_DIR}
    tar xf ${MARIADB_FILE}
    MARIADB_DIR=`echo ${MARIADB_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
    cd ${MARIADB_DIR}

    cmake . \
    -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \
    -DMYSQL_DATADIR=${DATA_DIR}/ \
    -DSYSCONFDIR=/etc/ \
    -DMYSQL_USER=mysql \
    -DWITH_INNOBASE_STORAGE_ENGINE=1 \
    -DWITH_ARCHIVE_STORAGE_ENGINE=1 \
    -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
    -DWITH_PARTITION_STORAGE_ENGINE=1 \
    -DWITHOUT_MROONGA_STORAGE_ENGINE=1 \
    -DWITH_DEBUG=0 \
    -DWITH_READLINE=1 \
    -DWITH_SSL=system \
    -DWITH_ZLIB=system \
    -DWITH_LIBWRAP=0 \
    -DENABLED_LOCAL_INFILE=1 \
    -DMYSQL_UNIX_ADDR=${DATA_DIR}/mysql.sock \
    -DDEFAULT_CHARSET=utf8 \
    -DDEFAULT_COLLATION=utf8_general_ci
    make -j ${CPUS} && make install
    [ $? -eq 0 ] && ${COLOR}"MariaDB编译安装成功"${END} ||  { ${COLOR}"MariaDB编译安装失败,退出!"${END};exit; }

	echo 'PATH='${INSTALL_DIR}'/bin:$PATH' > /etc/profile.d/mysql.sh
    .  /etc/profile.d/mysql.sh
    chown -R mysql.mysql ${INSTALL_DIR}

    cd ${INSTALL_DIR}
    ./scripts/mysql_install_db --datadir=${DATA_DIR} --user=mysql

    cat > /etc/my.cnf <<-EOF
[mysqld]
basedir=${INSTALL_DIR}
datadir=${DATA_DIR}
port=3306
socket=${DATA_DIR}/mysql.sock 
pid-file=${DATA_DIR}/mysql.pid 

[mysqld_safe]
log-error=${DATA_DIR}/mysql.log 

[mysql]
default-character-set=utf8mb4

[client]
port=3306
socket=${DATA_DIR}/mysql.sock
default-character-set=utf8mb4
EOF

    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        rpm -q chkconfig &> /dev/null || { ${COLOR}"安装chkconfig包,请稍等..."${END};yum -y install chkconfig &> /dev/null; }
    fi
    cp ${INSTALL_DIR}/support-files/mysql.server  /etc/init.d/mysqld
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        chkconfig --add mysqld
    else
        update-rc.d -f mysqld defaults
    fi
    cat > /lib/systemd/system/mysqld.service <<-EOF
[Unit]
Description=mysql database server
After=network.target

[Service]
Type=notify
PrivateNetwork=false
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
SuccessExitStatus=5 6
ExecStart=/etc/init.d/mysqld start
ExecStop=/etc/init.d//mysqld stop
ExecReload=/etc/init.d/mysqld reload

[Install]
WantedBy=multi-user.target
Alias=mysqld.service
EOF
    systemctl daemon-reload
    systemctl enable --now mysqld &> /dev/null
    [ $? -ne 0 ] && { ${COLOR}"数据库启动失败,退出!"${END};exit; }
    ${COLOR}"MySQL数据库安装完成"${END}
}

mysql_secure(){
    ${INSTALL_DIR}/bin/mysql_secure_installation <<EOF

y
y
${MYSQL_ROOT_PASSWORD}
${MYSQL_ROOT_PASSWORD}
y
y
y
y
EOF
}

main(){
    os
    check_file
    install_mysql
    mysql_secure
}

main

2.4 二进制安装安装MariaDB

2.4.1 用户和组

bash 复制代码
useradd -r -s /sbin/nologin -d /data/mysql mysql

2.4.2 准备程序文件

MariaDB源码包下载,去"mariadb.org//"网站下载,选择"Download"。

在弹出的网页,选择"MariaDB Server Version为:MariaDB Server 11.3.2",选择"Operating System为:Linux",选择"Architecture为:x86_64",选择"Init System为:Systemd",然后选下面的"Download"。

bash 复制代码
cd /usr/local/src/
wget https://mirrors.xtom.com.hk/mariadb//mariadb-11.3.2/bintar-linux-systemd-x86_64/mariadb-11.3.2-linux-systemd-x86_64.tar.gz

tar xf mariadb-11.3.2-linux-systemd-x86_64.tar.gz -C /usr/local

ln -s /usr/local/mariadb-11.3.2-linux-systemd-x86_64/ /usr/local/mysql

chown -R  mysql.mysql /usr/local/mysql/

2.4.3 准备环境变量

bash 复制代码
echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
. /etc/profile.d/mysql.sh

2.4.4 准备配置文件

ini 复制代码
cat > /etc/my.cnf <<-EOF
[mysqld]
datadir=/data/mysql
socket=/data/mysql/mysql.sock

[mysqld_safe]
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid

[client]
socket=/data/mysql/mysql.sock
EOF

2.4.5 生成数据库文件

bash 复制代码
mkdir -pv /data/mysql

chown -R  mysql.mysql /data/mysql

#这里必须先要进入/apps/mysql/目录,在执行下面命令
cd /usr/local/mysql/
./scripts/mysql_install_db --datadir=/data/mysql/ --user=mysql

2.4.6 准备服务脚本和启动

bash 复制代码
cp /usr/local/mysql/support-files/systemd/mysqld.service /lib/systemd/system/

systemctl daemon-reload && systemctl enable --now mysqld

2.4.7 安全初始化

vbnet 复制代码
# Rocky 8/9、CentOS 8/9和Ubuntu 22.04/20.04出现提示没有"libncurses.so.5"文件和没有"libtinfo.so.5"文件
[root@rocky9 ~]# mysql
mysql: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
# 提示没有"libncurses.so.5"文件

[root@rocky9 ~]# find / -name 'libncurses*'
/usr/lib64/libncurses.so.6
/usr/lib64/libncurses.so.6.2
/usr/lib64/libncursesw.so.6
/usr/lib64/libncursesw.so.6.2
# 找到了"libncurses.so.6"文件

# 把"libncurses.so.6"文件软链接到"libncurses.so.5"
[root@rocky9 ~]# ln -s /usr/lib64/libncurses.so.6 /usr/lib64/libncurses.so.5
[root@rocky9 ~]# ls -l /usr/lib64/libncurses.so.5
lrwxrwxrwx 1 root root 26 Feb 26 16:44 /usr/lib64/libncurses.so.5 -> /usr/lib64/libncurses.so.6

root@ubuntu2204:~# find / -name 'libncurses*'
/usr/lib/x86_64-linux-gnu/libncursesw.so.6
/usr/lib/x86_64-linux-gnu/libncurses.so.6
/usr/lib/x86_64-linux-gnu/libncursesw.so.6.3
/usr/lib/x86_64-linux-gnu/libncurses.so.6.3
root@ubuntu2204:~# ln -s /usr/lib/x86_64-linux-gnu/libncurses.so.6 /usr/lib/x86_64-linux-gnu/libncurses.so.5
root@ubuntu2204:~# ls -l /usr/lib/x86_64-linux-gnu/libncurses.so.5
lrwxrwxrwx 1 root root 41 Feb 26 17:40 /usr/lib/x86_64-linux-gnu/libncurses.so.5 -> /usr/lib/x86_64-linux-gnu/libncurses.so.6

[root@rocky9 ~]# mysql
mysql: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory
# 提示没有"libtinfo.so.5"文件

[root@rocky9 ~]# find / -name 'libtinfo*'
/usr/lib64/libtinfo.so.6
/usr/lib64/libtinfo.so.6.2
# 找到了"libtinfo.so.6"文件

# 把"libtinfo.so.6"文件软链接到"libtinfo.so.5"
[root@rocky9 ~]# ln -s /usr/lib64/libtinfo.so.6 /usr/lib64/libtinfo.so.5
[root@rocky9 ~]# ls -l /usr/lib64/libtinfo.so.5
lrwxrwxrwx 1 root root 24 Feb 26 16:46 /usr/lib64/libtinfo.so.5 -> /usr/lib64/libtinfo.so.6

root@ubuntu2204:~# find / -name 'libtinfo*'
/usr/lib/x86_64-linux-gnu/libtinfo.so.6.3
/usr/lib/x86_64-linux-gnu/libtinfo.so.6
root@ubuntu2204:~# ln -s /usr/lib/x86_64-linux-gnu/libtinfo.so.6 /usr/lib/x86_64-linux-gnu/libtinfo.so.5
root@ubuntu2204:~# ls -l /usr/lib/x86_64-linux-gnu/libtinfo.so.5
lrwxrwxrwx 1 root root 39 Feb 26 17:39 /usr/lib/x86_64-linux-gnu/libtinfo.so.5 -> /usr/lib/x86_64-linux-gnu/libtinfo.so.6

[root@rocky9 ~]# mysql
mysql: Deprecated program name. It will be removed in a future release, use '/usr/local/mariadb-11.3.2-linux-systemd-x86_64/bin/mariadb' instead
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 11.3.2-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status
--------------
mysql from 11.3.2-MariaDB, client 15.2 for linux-systemd (x86_64) using readline 5.1

Connection id:		4
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		11.3.2-MariaDB MariaDB Server
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8mb3
Conn.  characterset:	utf8mb3
UNIX socket:		/data/mysql/mysql.sock
Uptime:			6 min 42 sec

Threads: 1  Questions: 5  Slow queries: 0  Opens: 17  Open tables: 10  Queries per second avg: 0.012
--------------

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.000 sec)

MariaDB [(none)]> select user,host from mysql.user;
+-------------+-----------+
| User        | Host      |
+-------------+-----------+
| PUBLIC      |           |
|             | localhost |
| mariadb.sys | localhost |
| mysql       | localhost |
| root        | localhost |
|             | rocky9    |
+-------------+-----------+
6 rows in set (0.001 sec)

MariaDB [(none)]> exit
Bye

# Rocky 8/9、CentOS 7/8/9和Ubuntu 22.04/20.04/18.04出现提示没有"/tmp/mysql.sock"文件
[root@rocky9 ~]# mysql_secure_installation
/usr/local/mysql/bin/mysql_secure_installation: Deprecated program name. It will be removed in a future release, use 'mariadb-secure-installation' instead

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
ERROR 2002 (HY000): Can't connect to local server through socket '/tmp/mysql.sock' (2)
# 提示没有"/tmp/mysql.sock"文件

# 创建软链接
[root@rocky9 ~]# ln -s /data/mysql/mysql.sock /tmp/mysql.sock

[root@rocky9 ~]# mysql_secure_installation
/usr/local/mysql/bin/mysql_secure_installation: Deprecated program name. It will be removed in a future release, use 'mariadb-secure-installation' instead

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] y
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

2.4.8 测试登录

sql 复制代码
[root@rocky9 ~]# mysql -uroot -p123456
mysql: Deprecated program name. It will be removed in a future release, use '/usr/local/mariadb-11.3.2-linux-systemd-x86_64/bin/mariadb' instead
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 15
Server version: 11.3.2-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status
--------------
mysql from 11.3.2-MariaDB, client 15.2 for linux-systemd (x86_64) using readline 5.1

Connection id:		15
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server:			MariaDB
Server version:		11.3.2-MariaDB MariaDB Server
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8mb3
Conn.  characterset:	utf8mb3
UNIX socket:		/data/mysql/mysql.sock
Uptime:			19 min 30 sec

Threads: 1  Questions: 31  Slow queries: 0  Opens: 21  Open tables: 14  Queries per second avg: 0.026
--------------

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.001 sec)

MariaDB [(none)]> select user,host from mysql.user;
+-------------+-----------+
| User        | Host      |
+-------------+-----------+
| PUBLIC      |           |
| mariadb.sys | localhost |
| mysql       | localhost |
| root        | localhost |
+-------------+-----------+
4 rows in set (0.001 sec)

MariaDB [(none)]> exit
Bye

2.4.9 一键安装MariaDB二进制包的脚本

Shell脚本源码地址:

Gitee:gitee.com/raymond9/sh...

Github:github.com/raymond9999...

可以去上面的Gitee或Github代码仓库拉取脚本。

bash 复制代码
[root@rocky9 ~]# install_mariadb_binary.sh
#!/bin/bash
#
#************************************************************************************************************
#Author:        Raymond
#QQ:            88563128
#Date:          2024-02-26
#FileName:      install_mariadb_binary.sh
#URL:           raymond.blog.csdn.net
#Description:   install_mysql_binary for CentOS 7 & CentOS Stream 8/9 & Ubuntu 18.04/20.04/22.04 & Rocky 8/9
#Copyright (C): 2024 All rights reserved
#************************************************************************************************************
SRC_DIR=/usr/local/src
COLOR="echo -e \033[01;31m"
END='\033[0m'
DATA_DIR=/data/mysql
MARIADB_URL=https://mirrors.xtom.com.hk/mariadb//mariadb-11.3.2/bintar-linux-systemd-x86_64/
MARIADB_FILE='mariadb-11.3.2-linux-systemd-x86_64.tar.gz'

os(){
    OS_ID=`sed -rn '/^NAME=/s@.*="([[:alpha:]]+).*"$@\1@p' /etc/os-release`
    OS_RELEASE_VERSION=`sed -rn '/^VERSION_ID=/s@.*="?([0-9]+).?.*"?@\1@p' /etc/os-release`
}

check_file(){
    cd  ${SRC_DIR}
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        rpm -q wget &> /dev/null || { ${COLOR}"安装wget工具,请稍等..."${END};yum -y install wget &> /dev/null; }
    fi
    if [ ! -e ${MARIADB_FILE} ];then
        ${COLOR}"缺少${MARIADB_FILE}文件"${END}
        ${COLOR}'开始下载MariaDB二进制安装包'${END}
        wget ${MARIADB_URL}${MARIADB_FILE} || { ${COLOR}"MariaDB二进制安装包下载失败"${END}; exit; }
    else
        ${COLOR}"${MARIADB_FILE}文件已准备好"${END}
    fi
}

install_mysql(){
    [ -d /usr/local/mysql ] && { ${COLOR}"MariaDB数据库已存在,安装失败"${END};exit; }
    ${COLOR}"开始安装MariaDB数据库..."${END}
    id mysql &> /dev/null || { useradd -r -s /sbin/nologin -d ${DATA_DIR} mysql ; ${COLOR}"创建mysql用户"${END}; }
    tar xf ${MARIADB_FILE} -C /usr/local/
    MARIADB_DIR=`echo ${MARIADB_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
    ln -s  /usr/local/${MARIADB_DIR} /usr/local/mysql
    chown -R mysql.mysql /usr/local/mysql/
    echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
    . /etc/profile.d/mysql.sh
    cat > /etc/my.cnf <<-EOF
[mysqld]
datadir=${DATA_DIR}
socket=${DATA_DIR}/mysql.sock

[mysqld_safe]
log-error=${DATA_DIR}/mysql.log
pid-file=${DATA_DIR}/mysql.pid

[client]
socket=${DATA_DIR}/mysql.sock
EOF
    [ -d ${DATA_DIR} ] || mkdir -p ${DATA_DIR} &> /dev/null
    chown -R  mysql.mysql ${DATA_DIR}
    cd /usr/local/mysql
    ./scripts/mysql_install_db --datadir=${DATA_DIR} --user=mysql
    cp /usr/local/mysql/support-files/systemd/mysqld.service /lib/systemd/system/
    systemctl daemon-reload
    systemctl enable --now mysqld &> /dev/null
    [ $? -ne 0 ] && { ${COLOR}"数据库启动失败,退出!"${END};exit; }
    if [ ${OS_RELEASE_VERSION} == 8 -o ${OS_RELEASE_VERSION} == 9 ] &> /dev/null;then
        ln -s /usr/lib64/libncurses.so.6 /usr/lib64/libncurses.so.5
        ln -s /usr/lib64/libtinfo.so.6 /usr/lib64/libtinfo.so.5
    fi
    if [ ${OS_RELEASE_VERSION} == 20 -o ${OS_RELEASE_VERSION} == 22 ] &> /dev/null;then
        ln -s /usr/lib/x86_64-linux-gnu/libncurses.so.6 /usr/lib/x86_64-linux-gnu/libncurses.so.5
        ln -s /usr/lib/x86_64-linux-gnu/libtinfo.so.6 /usr/lib/x86_64-linux-gnu/libtinfo.so.5
    fi
    ln -s /data/mysql/mysql.sock /tmp/mysql.sock
    ${COLOR}"MariaDB数据库安装完成"${END}

}

mysql_secure(){
    /usr/local/mysql/bin/mysql_secure_installation <<EOF

y
y
${MYSQL_ROOT_PASSWORD}
${MYSQL_ROOT_PASSWORD}
y
y
y
y
EOF
}

main(){
    os
    check_file
    install_mysql
    mysql_secure
}

main
相关推荐
ZHOUPUYU14 分钟前
Centos常用命令,按功能分类,用户和权限管理等
linux·运维·centos
vvw&33 分钟前
如何在 Ubuntu 22.04 上安装 phpMyAdmin
linux·运维·服务器·mysql·ubuntu·php·phpmyadmin
SEO-狼术37 分钟前
Enhance Security in Software Crack
数据库
计算机毕设定制辅导-无忧学长1 小时前
Redis 初相识:开启缓存世界大门
数据库·redis·缓存
Rverdoser1 小时前
redis延迟队列
数据库·redis·缓存
灰勒塔德2 小时前
Linux文件IO
linux·运维·服务器
weisian1512 小时前
Redis篇--常见问题篇6--缓存一致性1(Mysql和Redis缓存一致,更新数据库删除缓存策略)
数据库·redis·缓存
dntktop2 小时前
解锁自动化新高度,zTasker v2.0全方位提升效率
运维·windows
运维&陈同学3 小时前
【Beats01】企业级日志分析系统ELK之Metricbeat与Heartbeat 监控
运维·elk·elasticsearch·云原生·kibana·heartbeat·metricbeat
中草药z3 小时前
【Spring】深入解析 Spring 原理:Bean 的多方面剖析(源码阅读)
java·数据库·spring boot·spring·bean·源码阅读