作者简介
马听,多年 DBA 经验,对MySQL、 Redis、MongoDB、Go等有一定了解,书籍《MySQL DBA精英实战课》作者,慕课网DBA体系课(https://class.imooc.com/sale/dba)讲师。
英雄联盟S3赛季排位青铜五0胜点(当时没有更低段位了)选手。
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 = 3306socket = tmp/mysql.sock[mysqld]port = 3306socket = tmp/mysql.sock## dir setdatadir = data/mysql/datainnodb_data_home_dir = data/mysql/datainnodb_log_group_home_dir = data/mysql/datalog-bin = data/mysql/binlog/mysql-binlog_bin_index = data/mysql/binlog/mysql-bin.indexrelay-log = data/mysql/binlog/mysql-relay-bintmpdir = data/mysql/tmpdirslow_query_log_file = data/mysql/log/mysql-slow.loggeneral_log_file = data/mysql/log/mysql-general.loglog-error = data/mysql/log/mysql.err## slave and binlogserver-id = 6666 #skip-slave-start = 0 #read_only = 0 #binlog_format = rowlog-slave-updates = 1master_info_repository = tablerelay_log_info_repository = tablerelay_log_purge = 1relay_log_recovery = 1sync_binlog = 100 # !!!binlog_cache_size = 1Mexpire_logs_days = 30log_bin_trust_function_creators = 1slave_net_timeout=60#binlog_error_action="IGNORE_ERROR"innodb_autoinc_lock_mode=1##back_log = 200bulk_insert_buffer_size = 8M#character-set-server = utf8lower_case_table_names = 1 # 1:不区分## 基线local-infile = offskip-networking = offskip-name-resolve = on## connectmax_allowed_packet = 32Mmax_connect_errors = 1000max_connections = 3000wait_timeout = 3600 # 关闭 非交互 连接之前等待活动的秒数 default:8hinteractive_timeout = 3600 # 关闭 交互式 连接之前等待活动的秒数 default:8htable_open_cache = 4096thread_cache_size = 64thread_stack = 192Ktransaction-isolation = REPEATABLE-READ #pid-file = mysql.pid## slowslow_query_log = 1long_query_time = 1log-slow-admin-statementslog_queries_not_using_indexes = 0slow_launch_time = 1read_buffer_size = 4Mread_rnd_buffer_size = 8Msort_buffer_size = 8Mjoin_buffer_size = 32Mtmp_table_size = 128Mmax_heap_table_size = 128Mdefault-storage-engine = innodbexplicit_defaults_for_timestamp = on## innodbinnodb_buffer_pool_size = 1Ginnodb_max_dirty_pages_pct = 80innodb_thread_concurrency = 8innodb_buffer_pool_instances = 1innodb_flush_log_at_trx_commit = 2innodb_read_io_threads = 8innodb_write_io_threads = 4innodb_io_capacity = 1000innodb_io_capacity_max = 2000innodb_lru_scan_depth = 1024innodb_use_native_aio = 1innodb_flush_neighbors = 1innodb_buffer_pool_load_at_startup = 1innodb_buffer_pool_dump_at_shutdown = 1innodb_data_file_path=ibdata:1G:autoextendinnodb_log_files_in_group = 3innodb_log_file_size = 2Ginnodb_file_per_table = 1innodb_flush_method = O_DIRECTinnodb_strict_mode = 1innodb_lock_wait_timeout = 30innodb_log_buffer_size = 16Minnodb_adaptive_flushing = 1innodb_change_buffering = allinnodb_purge_threads = 4innodb_purge_batch_size = 300innodb_old_blocks_time = 1innodb_fast_shutdown = 0performance_schema = 1innodb_print_all_deadlocks = 1innodb_sort_buffer_size = 4Minnodb_page_size = 16kgtid_mode=onenforce_gtid_consistency=ontable_open_cache_instances=16binlog_rows_query_log_events=1slave_parallel_workers = 0 # 多线程复制线程数#slave_parallel_type=LOGICAL_CLOCK#binlog_group_commit_sync_delay = 500000#binlog_group_commit_sync_no_delay_count =12## pasworddefault_password_lifetime=0 # 0密码永不过期,N n天过期[mysqldump]quickmax_allowed_packet = 32M[mysql]no-auto-rehashprompt=\p@\d>\_[mysqld_safe]open-files-limit = 28192[mysqlhotcopy]interactive-timeout
3 配置启动脚本
vim mysql.server
加入如下内容:
#!/bin/shbasedir=datadir=/data/mysql/dataconfdir=/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 indefinitelyservice_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 defaultsmysqld_pid_file_path=if test -z "$basedir"thenbasedir=/usr/local/mysqlbindir=/usr/local/mysql/binif test -z "$datadir"thendatadir=/usr/local/mysql/datafisbindir=/usr/local/mysql/binlibexecdir=/usr/local/mysql/binelsebindir="$basedir/bin"if test -z "$datadir"thendatadir="$basedir/data"fisbindir="$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_functionselselog_success_msg(){echo " SUCCESS! $@"}log_failure_msg(){echo " ERROR! $@"}fiPATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"export PATHmode=$1 # start or stop[ $# -ge 1 ] && shiftother_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' ;;esacparse_server_arguments() {for arg docase "$arg" in--basedir=*) basedir=`echo "$arg" | sed -e 's/^[^=]*=//'`bindir="$basedir/bin"if test -z "$datadir_set"; thendatadir="$basedir/data"fisbindir="$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/^[^=]*=//'` ;;esacdone}wait_for_pid () {verb="$1" # created | removedpid="$2" # process ID of the program operating on the pid-filepid_file_path="$3" # path to the PID file.i=0avoid_race_condition="by checking again"while test $i -ne $service_startup_timeout ; docase "$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 disappeartest ! -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 updatedif test -n "$pid"; thenif kill -0 "$pid" 2>/dev/null; then: # the server still runselse# The server may have exited between the last pid-file check and now.if test -n "$avoid_race_condition"; thenavoid_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.fifiecho $echo_n ".$echo_c"i=`expr $i + 1`sleep 1doneif test -z "$i" ; thenlog_success_msgreturn 0elselog_failure_msgreturn 1fi}# 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"; thenprint_defaults="$bindir/my_print_defaults"else# Try to find basedir in etc/my.cnfconf=/etc/my.cnfprint_defaults=if test -r $confthensubpat='^[^=]*basedir[^=]*=\(.*\)$'dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf`for d in $dirsdod=`echo $d | sed -e 's/[ ]//g'`if test -x "$d/bin/my_print_defaults"thenprint_defaults="$d/bin/my_print_defaults"breakfidonefi# Hope it's in the PATH ... but I doubt ittest -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"thenextra_args="-e $basedir/my.cnf"fiparse_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"thenmysqld_pid_file_path=$datadir/`hostname`.pidelsecase "$mysqld_pid_file_path" in* ) ;;* ) mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;;esacficase "$mode" in'start')# Start daemon# Safeguard (relative paths, core dumps..)cd $basedirecho $echo_n "Starting MySQL"if test -x $bindir/mysqld_safethen# 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 SuSEif test -w "$lockdir"thentouch "$lock_file_path"fiexit $return_valueelselog_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 stoptouch "$mysqld_pid_file_path.shutdown"mysqld_pid=`cat "$mysqld_pid_file_path"`if (kill -0 $mysqld_pid 2>/dev/null)thenecho $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=$?elselog_failure_msg "MySQL server process #$mysqld_pid is not running!"rm "$mysqld_pid_file_path"fi# Delete lock for RedHat SuSEif test -f "$lock_file_path"thenrm -f "$lock_file_path"fiexit $return_valueelselog_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_argselselog_failure_msg "Failed to stop running server, so refusing to try to start."exit 1fi;;'reload'|'force-reload')if test -s "$mysqld_pid_file_path" ; thenread mysqld_pid < "$mysqld_pid_file_path"kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL"touch "$mysqld_pid_file_path"elselog_failure_msg "MySQL PID file could not be found!"exit 1fi;;'status')# First, check to see if pid file existsif test -s "$mysqld_pid_file_path" ; thenread mysqld_pid < "$mysqld_pid_file_path"if kill -0 $mysqld_pid 2>/dev/null ; thenlog_success_msg "MySQL running ($mysqld_pid)"exit 0elselog_failure_msg "MySQL is not running, but PID file exists"exit 1fielse# Try to find appropriate mysqld processmysqld_pid=`pidof $libexecdir/mysqld`# test if multiple pids existpid_count=`echo $mysqld_pid | wc -w`if test $pid_count -gt 1 ; thenlog_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)"exit 5elif test -z $mysqld_pid ; thenif test -f "$lock_file_path" ; thenlog_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists"exit 2filog_failure_msg "MySQL is not running"exit 3elselog_failure_msg "MySQL is running but PID file could not be found"exit 4fifi;;*)# usagebasename=`basename "$0"`echo "Usage: $basename {start|stop|restart|reload|force-reload|status} [ MySQL server options ]"exit 1;;esacexit 0
4 配置MySQL安装脚本
新建脚本
vim install_mysql.sh
加入如下内容:
#!/bin/bash# 解压if [ -d "/usr/local/mysql" ];thenecho "/usr/local/mysql文件夹已经存在,请确定是否安装了MySQL"exitfiecho "正在解压压缩包"tar xf mysql-8.0.25-linux-glibc2.12-x86_64.tarmv mysql-8.0.25-linux-glibc2.12-x86_64 usr/local/mysqlecho "压缩包解压完毕"# 创建MySQL相关目录if [ -d "/data/mysql/" ];thenecho "/data/mysql文件夹已经存在,请确定是否安装了MySQL"exitfimkdir data/mysql/{binlog,data,log,tmpdir,conf} -p# 判断是否有MySQL进程mysql_pid=`ps -ef|grep mysqld|wc -l`if [ $mysql_pid -eq 1 ];thenecho "MySQL进程没有运行"elseecho "有MySQL进程运行,请检查"exitfi#创建MySQL用户mysql_user=`cat etc/passwd|grep -w mysql|wc -l`if [ $mysql_user -eq 1 ];thenecho "MySQL用户已经存在"elseecho "MySQL用户不存在,开始添加MySQL用户"groupadd mysqluseradd -g mysql mysqlecho "添加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 ];thenecho "mysql 初始化成功"elseecho "mysql 初始化失败"exitfi# 获取临时密码temp_pwd=$(grep 'temporary password' /data/mysql/log/mysql.err)pwd=${temp_pwd##* }echo "临时密码是:${pwd}"# 配置启动脚本if [ ! -f "/etc/init.d/mysql.server" ];thencp mysql.server /etc/init.d/ -rfchmod 700 /etc/init.d/mysql.serverfi# 启动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 ];thenecho "export PATH=\$PATH:/usr/local/mysql/bin" >> /etc/profilesource /etc/profilefi# 通过临时密码登录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行)
最近原创干货
我们创建了 MySQL 交流社群,围绕开发、运维、DBA、架构师和其他需要用到 MySQL 的群体。
入群请加下方群秘微信,回复“进MySQL群”

推荐文章👇
试看号主的拙作《MySQL 8.0运维与优化》(清华大学出版社)
托业890分的Oracle ACE为您翻译国际大佬的雄文(合集)
文章转载自oracleace,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




