1 下载安装包

首先,我们下载MySQL 8.0.25的安装包:

wget https://downloads.mysql.com/archives/get/p/23/file/mysql-8.0.25-linux-glibc2.12-x86_64.tar.xz


再解压这个xz文件

xz -d mysql-8.0.25-linux-glibc2.12-x86_64.tar.xz

2 编辑配置文件模板

vim my.cnf

加入如下内容:

[client]
port        = 3306
socket      = /tmp/mysql.sock

[mysqld]
port    = 3306
socket  = /tmp/mysql.sock

##  dir set
datadir           = /data/mysql/data
innodb_data_home_dir   = /data/mysql/data
innodb_log_group_home_dir = /data/mysql/data
log-bin           = /data/mysql/binlog/mysql-bin
log_bin_index             = /data/mysql/binlog/mysql-bin.index  
relay-log         = /data/mysql/binlog/mysql-relay-bin
tmpdir            = /data/mysql/tmpdir
slow_query_log_file   = /data/mysql/log/mysql-slow.log
general_log_file   = /data/mysql/log/mysql-general.log
log-error         = /data/mysql/log/mysql.err

## slave and binlog
server-id = 6666            #  
skip-slave-start = 0        #
read_only = 0           #
binlog_format = row            
log-slave-updates = 1
master_info_repository = table
relay_log_info_repository = table
relay_log_purge = 1
relay_log_recovery = 1
sync_binlog = 100                   # !!!

binlog_cache_size = 1M
expire_logs_days = 30
log_bin_trust_function_creators = 1        
slave_net_timeout=60                
#binlog_error_action="IGNORE_ERROR"    

innodb_autoinc_lock_mode=1          

##
back_log = 200
bulk_insert_buffer_size = 8M            
#character-set-server = utf8
lower_case_table_names = 1              #  1:不区分

## 基线
local-infile = off
skip-networking = off
skip-name-resolve = on

## connect
max_allowed_packet = 32M
max_connect_errors = 1000
max_connections = 3000
wait_timeout = 3600             # 关闭 非交互 连接之前等待活动的秒数 default:8h
interactive_timeout = 3600          # 关闭 交互式 连接之前等待活动的秒数 default:8h

table_open_cache = 4096
thread_cache_size =  64
thread_stack = 192K
transaction-isolation = REPEATABLE-READ     #
pid-file = mysql.pid

## slow
slow_query_log = 1              
long_query_time = 1
log-slow-admin-statements
log_queries_not_using_indexes = 0
slow_launch_time = 1
read_buffer_size = 4M              
read_rnd_buffer_size = 8M          
sort_buffer_size = 8M
join_buffer_size = 32M
tmp_table_size = 128M
max_heap_table_size = 128M

default-storage-engine = innodb
explicit_defaults_for_timestamp = on          

## innodb
innodb_buffer_pool_size = 1G                    
innodb_max_dirty_pages_pct = 80        
innodb_thread_concurrency = 8          
innodb_buffer_pool_instances = 1        
innodb_flush_log_at_trx_commit = 2      
innodb_read_io_threads = 8          
innodb_write_io_threads = 4        
innodb_io_capacity = 1000
innodb_io_capacity_max = 2000
innodb_lru_scan_depth = 1024
innodb_use_native_aio = 1
innodb_flush_neighbors = 1
innodb_buffer_pool_load_at_startup = 1
innodb_buffer_pool_dump_at_shutdown = 1

innodb_data_file_path=ibdata:1G:autoextend
innodb_log_files_in_group = 3
innodb_log_file_size = 2G
innodb_file_per_table = 1

innodb_flush_method = O_DIRECT
innodb_strict_mode = 1
innodb_lock_wait_timeout = 30
innodb_log_buffer_size = 16M
innodb_adaptive_flushing = 1
innodb_change_buffering = all
innodb_purge_threads = 4            
innodb_purge_batch_size = 300          

innodb_old_blocks_time = 1
innodb_fast_shutdown = 0
performance_schema = 1
innodb_print_all_deadlocks = 1
innodb_sort_buffer_size = 4M

innodb_page_size = 16k
gtid_mode=on
enforce_gtid_consistency=on    

table_open_cache_instances=16
binlog_rows_query_log_events=1      

slave_parallel_workers = 0          # 多线程复制线程数
#slave_parallel_type=LOGICAL_CLOCK      
#binlog_group_commit_sync_delay = 500000  
#binlog_group_commit_sync_no_delay_count =12  

## pasword
default_password_lifetime=0                     # 0密码永不过期,N n天过期

[mysqldump]
quick
max_allowed_packet = 32M

[mysql]
no-auto-rehash
prompt=\p@\d>\_

[mysqld_safe]
open-files-limit = 28192

[mysqlhotcopy]
interactive-timeout

3 配置启动脚本

vim mysql.server

加入如下内容:

#!/bin/sh

basedir=
datadir=/data/mysql/data
confdir=/data/mysql/conf

# Default value, in seconds, afterwhich the script should timeout waiting
# for server start.
# Value here is overriden by value in my.cnf.
# 0 means don't wait at all
# Negative numbers mean to wait indefinitely
service_startup_timeout=900

# Lock directory for RedHat / SuSE.
lockdir='/var/lock/subsys'
lock_file_path="$lockdir/mysql"

# The following variables are only set for letting mysql.server find things.

# Set some defaults
mysqld_pid_file_path=
if test -z "$basedir"
then
 basedir=/usr/local/mysql
 bindir=/usr/local/mysql/bin
 if test -z "$datadir"
 then
   datadir=/usr/local/mysql/data
 fi
 sbindir=/usr/local/mysql/bin
 libexecdir=/usr/local/mysql/bin
else
 bindir="$basedir/bin"
 if test -z "$datadir"
 then
   datadir="$basedir/data"
 fi
 sbindir="$basedir/sbin"
 libexecdir="$basedir/libexec"
fi

# datadir_set is used to determine if datadir was set (and so should be
# *not* set inside of the --basedir= handler.)
datadir_set=

#
# Use LSB init script functions for printing messages, if possible
#
lsb_functions="/lib/lsb/init-functions"
if test -f $lsb_functions ; then
. $lsb_functions
else
 log_success_msg()
 {
   echo " SUCCESS! $@"
 }
 log_failure_msg()
 {
   echo " ERROR! $@"
 }
fi

PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"
export PATH

mode=$1    # start or stop

[ $# -ge 1 ] && shift

other_args="$*"   # uncommon, but needed when called from an RPM upgrade action
          # Expected: "--skip-networking --skip-grant-tables"
          # They are not checked here, intentionally, as it is the resposibility
          # of the "spec" file author to give correct arguments only.

case `echo "testing\c"`,`echo -n testing` in
*c*,-n*) echo_n=   echo_c=     ;;
   *c*,*)   echo_n=-n echo_c=     ;;
   *)       echo_n=   echo_c='\c' ;;
esac

parse_server_arguments() {
 for arg do
   case "$arg" in
--basedir=*)  basedir=`echo "$arg" | sed -e 's/^[^=]*=//'`
                   bindir="$basedir/bin"
       if test -z "$datadir_set"; then
         datadir="$basedir/data"
       fi
       sbindir="$basedir/sbin"
       libexecdir="$basedir/libexec"
       ;;
     --datadir=*)  datadir="/data/mysql/data"
       datadir_set=1
       ;;
     --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
     --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
   esac
 done
}

wait_for_pid () {
verb="$1"           # created | removed
 pid="$2"            # process ID of the program operating on the pid-file
 pid_file_path="$3" # path to the PID file.

 i=0
 avoid_race_condition="by checking again"

 while test $i -ne $service_startup_timeout ; do

   case "$verb" in
     'created')
       # wait for a PID-file to pop into existence.
       test -s "$pid_file_path" && i='' && break
;;
     'removed')
       # wait for this PID-file to disappear
       test ! -s "$pid_file_path" && i='' && break
;;
     *)
       echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path"
       exit 1
;;
   esac

   # if server isn't running, then pid-file will never be updated
   if test -n "$pid"; then
     if kill -0 "$pid" 2>/dev/null; then
:  # the server still runs
     else
       # The server may have exited between the last pid-file check and now.  
       if test -n "$avoid_race_condition"; then
         avoid_race_condition=""
         continue  # Check again.
         fi

       # there's nothing that will affect the file.
       log_failure_msg "The server quit without updating PID file ($pid_file_path)."
       return 1  # not waiting any more.
     fi
   fi

   echo $echo_n ".$echo_c"
   i=`expr $i + 1`
   sleep 1

 done

 if test -z "$i" ; then
   log_success_msg
   return 0
 else
   log_failure_msg
   return 1
 fi
}

# Get arguments from the my.cnf file,
# the only group, which is read from now on is [mysqld]
if test -x "$bindir/my_print_defaults";  then
 print_defaults="$bindir/my_print_defaults"
else
 # Try to find basedir in /etc/my.cnf
 conf=/etc/my.cnf
 print_defaults=
 if test -r $conf
 then
   subpat='^[^=]*basedir[^=]*=\(.*\)$'
   dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf`
   for d in $dirs
   do
       d=`echo $d | sed -e 's/[   ]//g'`
     if test -x "$d/bin/my_print_defaults"
     then
       print_defaults="$d/bin/my_print_defaults"
       break
       fi
   done
 fi

 # Hope it's in the PATH ... but I doubt it
 test -z "$print_defaults" && print_defaults="my_print_defaults"
fi

#
# Read defaults file from 'basedir'.   If there is no defaults file there
# check if it's in the old (depricated) place (datadir) and read it from there
#

extra_args=""
if test -r "$basedir/my.cnf"
then
 extra_args="-e $basedir/my.cnf"
fi

parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`

#
# Set pid file if not given
#
if test -z "$mysqld_pid_file_path"
then
 mysqld_pid_file_path=$datadir/`hostname`.pid
else
 case "$mysqld_pid_file_path" in
   /* ) ;;
   * )  mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;;
 esac
fi

case "$mode" in
 'start')
   # Start daemon

   # Safeguard (relative paths, core dumps..)
   cd $basedir

   echo $echo_n "Starting MySQL"
   if test -x $bindir/mysqld_safe
   then
     # Give extra arguments to mysqld with the my.cnf file. This script
     # may be overwritten at next upgrade.
     $bindir/mysqld_safe --defaults-file=$confdir/my.cnf --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null &
     wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

     # Make lock for RedHat / SuSE
     if test -w "$lockdir"
     then
       touch "$lock_file_path"
     fi

     exit $return_value
   else
     log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
   fi
   ;;

 'stop')
   # Stop daemon. We use a signal here to avoid having to know the
   # root password.

   if test -s "$mysqld_pid_file_path"
   then
     # signal mysqld_safe that it needs to stop
     touch "$mysqld_pid_file_path.shutdown"

     mysqld_pid=`cat "$mysqld_pid_file_path"`

     if (kill -0 $mysqld_pid 2>/dev/null)
     then
       echo $echo_n "Shutting down MySQL"
       kill $mysqld_pid
       # mysqld should remove the pid file when it exits, so wait for it.
       wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$?
     else
       log_failure_msg "MySQL server process #$mysqld_pid is not running!"
       rm "$mysqld_pid_file_path"
     fi

     # Delete lock for RedHat / SuSE
     if test -f "$lock_file_path"
     then
       rm -f "$lock_file_path"
     fi
     exit $return_value
   else
     log_failure_msg "MySQL server PID file could not be found!"
   fi
   ;;

 'restart')
   # Stop the service and regardless of whether it was
   # running or not, start it again.
   if $0 stop  $other_args; then
     $0 start $other_args
   else
     log_failure_msg "Failed to stop running server, so refusing to try to start."
     exit 1
   fi
   ;;

 'reload'|'force-reload')
   if test -s "$mysqld_pid_file_path" ; then
     read mysqld_pid <  "$mysqld_pid_file_path"
     kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL"
     touch "$mysqld_pid_file_path"
   else
     log_failure_msg "MySQL PID file could not be found!"
     exit 1
   fi
   ;;
 'status')
   # First, check to see if pid file exists
   if test -s "$mysqld_pid_file_path" ; then
     read mysqld_pid < "$mysqld_pid_file_path"
     if kill -0 $mysqld_pid 2>/dev/null ; then
       log_success_msg "MySQL running ($mysqld_pid)"
       exit 0
     else
       log_failure_msg "MySQL is not running, but PID file exists"
       exit 1
     fi
   else
     # Try to find appropriate mysqld process
     mysqld_pid=`pidof $libexecdir/mysqld`

     # test if multiple pids exist
     pid_count=`echo $mysqld_pid | wc -w`
     if test $pid_count -gt 1 ; then
       log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)"
       exit 5
     elif test -z $mysqld_pid ; then
       if test -f "$lock_file_path" ; then
         log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists"
         exit 2
       fi
       log_failure_msg "MySQL is not running"
       exit 3
     else
       log_failure_msg "MySQL is running but PID file could not be found"
       exit 4
     fi
   fi
   ;;
   *)
     # usage
     basename=`basename "$0"`
     echo "Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]"
     exit 1
   ;;
esac

exit 0

4 配置MySQL安装脚本

新建脚本

vim install_mysql.sh

加入如下内容:

#!/bin/bash

# 解压
if [ -d "/usr/local/mysql" ];then
 echo "/usr/local/mysql文件夹已经存在,请确定是否安装了MySQL"
 exit
fi
echo "正在解压压缩包"
tar xf mysql-8.0.25-linux-glibc2.12-x86_64.tar
mv mysql-8.0.25-linux-glibc2.12-x86_64 /usr/local/mysql
echo "压缩包解压完毕"

# 创建MySQL相关目录
if [ -d "/data/mysql/" ];then
 echo "/data/mysql文件夹已经存在,请确定是否安装了MySQL"
 exit
fi
mkdir /data/mysql/{binlog,data,log,tmpdir,conf} -p

# 判断是否有MySQL进程
mysql_pid=`ps -ef|grep mysqld|wc -l`
if [ $mysql_pid -eq 1 ];then
 echo "MySQL进程没有运行"
else
 echo "MySQL进程运行,请检查"
 exit
fi

#创建MySQL用户
mysql_user=`cat /etc/passwd|grep -w mysql|wc -l`

if [ $mysql_user -eq 1 ];then
 echo "MySQL用户已经存在"
else
 echo "MySQL用户不存在,开始添加MySQL用户"
 groupadd mysql
 useradd -g mysql mysql
 echo "添加MySQL用户成功"
fi

# 修改权限
chown -R mysql.mysql /data/mysql/
chown -R mysql.mysql /usr/local/mysql

# 增加配置文件
cp ./my.cnf /data/mysql/conf/

# 初始化
echo "开始初始化"
   /usr/local/mysql/bin/mysqld --defaults-file=/data/mysql/conf/my.cnf --user=mysql --initialize

# 判断初始化是否成功
mysql_init=`cat /data/mysql/log/mysql.err|grep -i "root@localhost:"|wc -l`
if [ $mysql_init -eq 1 ];then
 echo "mysql 初始化成功"
else
 echo "mysql 初始化失败"
 exit
fi

# 获取临时密码
temp_pwd=$(grep 'temporary password' /data/mysql/log/mysql.err)
pwd=${temp_pwd##* }
echo "临时密码是:${pwd}"

# 配置启动脚本
if [ ! -f "/etc/init.d/mysql.server" ];then
 cp mysql.server /etc/init.d/ -rf
 chmod 700 /etc/init.d/mysql.server
fi

# 启动mysql
/etc/init.d/mysql.server start

# 增加环境变量
mysql_path=`grep 'export PATH=$PATH:/usr/local/mysql/bin' /etc/profile|wc -l`
if [ $mysql_path -eq 0 ];then
 echo "export PATH=\$PATH:/usr/local/mysql/bin" >> /etc/profile
 source /etc/profile
fi

# 通过临时密码登录MySQL,并修改密码
mysql -uroot -p${pwd} --connect-expired-password -e "alter user user() identified by 'martin';"
echo "MySQL8.0.25 安装完成"

5 使用脚本安装MySQL

如果要安装MySQL,直接执行脚本就行

sh install_mysql.sh

MySQL相关命令所在的目录是:/usr/local/mysql/bin

MySQL数据目录是/data/mysql/data/

Binlog存放的目录是/data/mysql/binlog/

错误日志,慢查询日志存放的目录是/data/mysql/log

配置文件是:/data/mysql/conf/my.cnf

root密码默认是:martin(要修改默认密码的话,在脚本83行)