最靠谱 - Linux+Mysql 绿色免安装版、离线安装

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 干过几年的行内人几乎够碰到过,要在客户的非干净的Linux上跑起来我们的程序,通常可能都会碰到老版mysql不能卸载(别人有数据再跑),新版又装不上这样辣手的问题,那么我们离线免安装版将是雪中送炭! 一.

工作几年的都碰到过吧,要在客户的不干净的Linux上部署程序,但经常会碰到已经有老版mysql在跑了,又不能卸载,新版又因为各种原因装不上,那么用离线免安装版将是希望!

一.准备:

mysql5.7或mysql8.0.18安装包下载
其他调优官方文档

二.环境搭建:

注: 为了能够快速搭建, 分享一个我已编写好的自动安装的脚本 (若执行ok了, 本文后续的详细步骤也就可忽略了).

『特别提醒: 此配置及脚本仅在Ubuntu19.10 CentOS7.4 CentOS6.9 + Mysql5.7 Mysql8.0.18 下测试通过, 建议在OS或mysql相差不大的版本下运行 !!!』

高版本mysql许多配置项已发生变化, 例如, 在mysql8.0.18下 lower_case_table_names 就只允许初始化时设置(我的配置文件里已注了).

首先新建安装脚本:

cd ${MYSQL_HOME}
mkdir script && vim script/mysqld-green-install.sh

然后粘上安装脚本内容, 使用root运行:

#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
# Version v2.0
set -e

# Generic macro defintions.
OS_INFO=$(cat /etc/*release|head -n 1)
MYSQL_BASE_DIR="$(cd "`dirname "$0"`"/..; pwd)"
cd $MYSQL_BASE_DIR
MYSQL_VERSION="$(echo $(bin/mysqld --version|awk -F mysqld '{print $2}'|awk -F '(' '{print $1}'))"
MYSQL_USER="wl4g_mysql"
MYSQL_GROUP="wl4g_mysql"
MYSQL_DATA_DIR="${MYSQL_BASE_DIR}/data/"
MYSQL_PLUGIN_DIR="${MYSQL_BASE_DIR}/lib/plugin/"
MYSQL_CONF_FILE="${MYSQL_BASE_DIR}/conf/my.cnf"
MYSQL_LOG_ERR="${MYSQL_BASE_DIR}/log/mysqld-${MYSQL_USER}.err"
MYSQL_LOG_BIN="${MYSQL_DATA_DIR}/mysqld-${MYSQL_USER}-logbin"
MYSQL_PID_FILE="${MYSQL_BASE_DIR}/run/mysqld-${MYSQL_USER}.pid"
MYSQL_SOCKET="${MYSQL_BASE_DIR}/run/mysqld-${MYSQL_USER}.sock"

if [ "$USER" != "root" ]; then
  echo "Use the root user to execution this script!"
  exit 2
fi

#
# Load user and system environments.
#
# [Note]: 1, Using $() has the same effect as `` double backslash, but the latter is more compatible in the UNIX kernel.
# {Note}: 2, When use set -e, when source /etc/profile is executed in centos6.xx, the process is interrupted. Only use `` backslash to run normal!
#

if [ -f "/etc/profile" ]; then # e.g. CentOS.x, Ubuntu.x
  `source /etc/profile`
fi
if [ -f "/etc/bashrc" ]; then # e.g. CentOS.x
  `source /etc/bashrc`
fi
if [ -f "/etc/bash.bashrc" ]; then # e.g. Ubuntu.x
  `source /etc/bash.bashrc`
fi
if [ -f "~/.bashrc" ]; then # e.g. CentOS.x, Ubuntu.x
  `source ~/.bashrc`
fi
if [ -f "~/.bash_profile" ]; then # e.g. CentOS.x
  `source ~/.bash_profile`
fi
if [ -f "~/.profile" ]; then # e.g. Ubuntu.x
  `source ~/.profile`
fi


#
# Get already running mysqld pids.
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
function getMysqldPids(){
  PIDS=$(ps -ef|grep ${MYSQL_BASE_DIR}|grep mysqld|grep -v grep|cut -c 9-15)
  echo $PIDS
  return 0
}


#
# Pre init of required directory and permission etc.
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function preInitInstall() {
  if [[ "$MYSQL_GROUP" != "root" && -z "$(grep "^$MYSQL_GROUP" /etc/group)" ]]; then
    groupadd $MYSQL_GROUP
  fi
  if [[ "$MYSQL_USER" != "root" && -z "$(grep "^$MYSQL_USER" /etc/passwd)" ]]; then
    useradd -g $MYSQL_GROUP $MYSQL_USER
  fi
  mkdir -p ${MYSQL_BASE_DIR}/data
  mkdir -p ${MYSQL_BASE_DIR}/conf
  mkdir -p ${MYSQL_BASE_DIR}/log
  mkdir -p ${MYSQL_BASE_DIR}/run
  # Grant access.
  chmod -R 755 ${MYSQL_BASE_DIR} && chown -R ${MYSQL_USER}:${MYSQL_GROUP} ${MYSQL_BASE_DIR}
}


#
# Initializing config of my.cnf
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInitConfiguration() {
cat<<EOF>${MYSQL_CONF_FILE}
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# For more setup recommendations or green installation guidelines,
# @see http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
port = 3306
# Configured at install time. See: script/mysqld_install.sh
#basedir = {MYSQL_HOME}
#datadir = {basedir}/data
#socket = {basedir}/run/mysqld-{MYSQL_USER}.sock
#pid-file = {basedir}/run/mysqld-{MYSQL_USER}.pid
#log-error = {basedir}/log/mysqld-{MYSQL_USER}.err

# To turn on a very important data integrity option: logging changes to the binary log between backups.
#log_bin = {basedir}/data/mysqld-{MYSQL_USER}-log.bin
expire_logs_days = 15
# Warning: Unsigned value 2147483648 adjusted to 1073741824, max allowed set to 1G ??
max_binlog_size = 1G
server_id = 1

# Ignore SQL condition case.(1:ignore)
# Note: When mysql8+, after initialization, is is not allowed to change this setting.
# @see http://blog.itpub.net/20893244/viewspace-2565069/
# @see https://bugs.mysql.com/bug.php?id=90695
#lower_case_table_names = 1

# Set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
innodb_buffer_pool_size = 6144M
max_allowed_packet = 1024M
#slave_max_allowed_packet = 2048M
max_connections = 2500

# To set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
explicit_defaults_for_timestamp = true

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links = 0

# Recommended in standard MySQL setup
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES


# @Deprecated of using script/mysqld_install.sh
# 
#[mysqld_safe]
# {datadir}/log/mysqld.log
#log-error = log/mysqld.log
# {datadir}/mysqld.pid
#pid-file = mysqld.pid
EOF
}


#
# Initializing mysqld data directory. 
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
# See: https://dev.mysql.com/doc/refman/5.7/en/data-directory-initialization.html#data-directory-initialization-server-actions
#
function doInitDBMetaData() {
  if [ ! -d "${MYSQL_DATA_DIR}/performance_schema" ]; then
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Initializing mysql datadir to '${MYSQL_DATA_DIR}', It may take about 10 ~ 60sec ......  "

    # Using --defaults-file=xx prevent loading exist default config: e.g. /etc/my.cnf
    INIT_CMD="${MYSQL_BASE_DIR}/bin/mysqld \
        --defaults-file=${MYSQL_CONF_FILE} \
      --initialize \
      --user=${MYSQL_USER} \
      --basedir=${MYSQL_BASE_DIR} \
      --datadir=${MYSQL_DATA_DIR} \
      --plugin-dir=${MYSQL_PLUGIN_DIR}"
    `${INIT_CMD}`
  else
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Skip initialize mysqld metadata, because dir of '${MYSQL_BASE_DIR}' the catalog has data, is it initialized?"
    exit 2
  fi
}


#
# Install system service.  (/etc/systemd/system/mysqld.service   or   /lib/systemd/system/mysqld.service)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallSystemdService(){
  SERVICE_D_FILE="/lib/systemd/system/mysqld.service"  # e.g. Ubuntu16.x-, CentOS7.x
  if [ -n "$(cat /etc/*release |grep NAME|grep 'Ubuntu 19')" ]; then  # Ubuntu16.x
    SERVICE_D_FILE="/etc/systemd/system/mysqld.service"
  fi
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Installing mysqld systemctl service ..."

  # Backing up older systemctl mysqld.service(if necessary).
  if [ -f "$SERVICE_D_FILE" ]; then
    BAK_SERVICE_D_FILE="${SERVICE_D_FILE}_"$(date +'%y%m%d%H%M%S')
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Backing up older install mysqld.service from '${SERVICE_D_FILE}' to '${BAK_SERVICE_D_FILE}"
    `mv ${SERVICE_D_FILE} ${BAK_SERVICE_D_FILE}`
  fi

cat<<EOF>$SERVICE_D_FILE
#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# Version v2.0
# MySQL ${MYSQL_VERSION} systemd service.

[Unit]
Description=MySQL ${MYSQL_VERSION} Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=fork
Environment=MYSQL_HOME="${MYSQL_BASE_DIR}"
User=${MYSQL_USER}
Group=${MYSQL_GROUP}
PIDFile=${MYSQL_PID_FILE}

ExecStart=/bin/sh -c "exec \${MYSQL_HOME}/bin/mysqld \\
--defaults-file=\${MYSQL_HOME}/conf/my.cnf \\
--basedir=\${MYSQL_HOME} \\
--datadir=${MYSQL_DATA_DIR} \\
--plugin-dir=${MYSQL_PLUGIN_DIR} \\
--user=${MYSQL_USER} \\
--log-error=${MYSQL_LOG_ERR} \\
--log_bin=${MYSQL_LOG_BIN} \\
--pid-file=${MYSQL_PID_FILE} \\
--socket=${MYSQL_SOCKET}"
#--skip-grant-tables

ExecReload=/bin/kill -s HUP \$MAINPID
StandardOutput=${MYSQL_BASE_DIR}/log/mysqld.out
StandardError=journal
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=5
TimeoutSec=600
Restart=always
PermissionsStartOnly=true
RuntimeDirectoryMode=755
PrivateTmp=false
EOF

    # Configure systemd service & startup.
    /bin/systemctl daemon-reload
    /bin/systemctl enable mysqld
    /bin/systemctl start mysqld
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Started $(getMysqldPids) on ${SERVICE_D_FILE}"
}


#
# Install init.d service.  (/etc/init.d/mysqld.service)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallInitdService() {
  SERVICE_D_FILE="/etc/init.d/mysqld.service"
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Fallback install init.d service to ${SERVICE_D_FILE} ... , because current OS: '${OS_INFO}' does not support systemctl dbus !"

  # Backing up older systemctl mysqld.service(if necessary).
  if [ -f "$SERVICE_D_FILE" ]; then
    BAK_SERVICE_D_FILE="${SERVICE_D_FILE}_"$(date +'%y%m%d%H%M%S')
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Backing up older install mysqld.service from '${SERVICE_D_FILE}' to '${BAK_SERVICE_D_FILE}"
    `mv ${SERVICE_D_FILE} ${BAK_SERVICE_D_FILE}`
  fi

cat<<EOF>$SERVICE_D_FILE
#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# Version v2.0
set -e

MYSQL_HOME=${MYSQL_BASE_DIR}
# Get the execution command arg1.
COMMAND=\$1

# Start function.
function start(){
  PIDS=\$(getPids) # Get current process code.
  if [ -z "\$PIDS" ]; then
    # When mysqld_safe starts mysqld, it does not auto create log.err
    touch ${MYSQL_LOG_ERR} && chown -R ${MYSQL_USER}:${MYSQL_GROUP} ${MYSQL_LOG_ERR}

    EXEC_CMD="\${MYSQL_HOME}/bin/mysqld_safe \\
    --defaults-file=\${MYSQL_HOME}/conf/my.cnf \\
    --basedir=\${MYSQL_HOME} \\
    --datadir=${MYSQL_DATA_DIR} \\
    --plugin-dir=${MYSQL_PLUGIN_DIR} \\
    --user=${MYSQL_USER} \\
    --log-error=${MYSQL_LOG_ERR} \\
    --log_bin=${MYSQL_LOG_BIN} \\
    --pid-file=${MYSQL_PID_FILE} \\
    --socket=${MYSQL_SOCKET} \\
    --open-files-limit=102400"
    #--skip-grant-tables
    nohup \$EXEC_CMD > \${MYSQL_HOME}/log/mysqld.out 2>&1 < /dev/null &

    echo -n "MySQL ${MYSQL_VERSION} Server starting ..."
    while true
    do
      PIDS=\$(getPids)
      if [ "\$PIDS" == "" ]; then
        echo -n ".";
        sleep 0.8;
      else
        /bin/echo \$PIDS >"${MYSQL_PID_FILE}"
        break;
      fi
    done
    echo -e "\nStarted on "\$PIDS
  else
    echo "MySQL ${MYSQL_VERSION} Server is running "\$PIDS
  fi
}

# Stop function.
function stop(){
  PIDS=\$(getPids) # Get current process code.
  if [ -z "\$PIDS" ]; then
    echo "No mysqld running!"
  else
    echo -n "mysqld stopping by \$PIDS ..."
    kill -s TERM \$PIDS
    while true
    do
      PIDS=\$(getPids)
      if [ "\$PIDS" == "" ]; then
        /bin/rm -rf ${MYSQL_PID_FILE}
        break;
      else
        echo -n ".";
        sleep 0.8;
      fi
    done
    echo -e "\nStop Mysqld successfully."
  fi
}

# Status function.
function status(){
  ps -ef | grep mysqld | grep -v grep | grep -i ${MYSQL_BASE_DIR}
}

# Got pids.
function getPids(){
  PIDS=\$(ps ax | grep mysqld | grep -i ${MYSQL_BASE_DIR} | grep -v grep | awk '{print \$1}')
  echo \$PIDS # Output execution result value.
  return 0 # Return the execution result code.
}

# Executive operations.
case \$COMMAND in
  status)
    status
    ;;
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
    *)
  echo $"Usage:{start|stop|restart|status}"
  exit 2
esac
EOF

  #   # Configure init.d service & startup.
  chmod 755 $SERVICE_D_FILE && ${SERVICE_D_FILE} start
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Started $(getMysqldPids) on ${SERVICE_D_FILE}"
}


#
# Install manager service.  (total)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallServiceAndStartup() {
  if [ -f "/bin/systemctl" ]; then  # Check sytemctl support?
    doInstallSystemdService
  else   # Using init.d service.
    doInstallInitdService
  fi
}


# Main green install.
preInitInstall
doInitConfiguration
doInitDBMetaData
doInstallServiceAndStartup

echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] MySQL ${MYSQL_VERSION} server system service installed successfully! \
please using '${SERVICE_D_FILE}' to management it.\n"

送佛送到西, 同时也把我自动卸载的脚本分享出来把(^_^):

vim script/mysqld-uninstall.sh

然后粘上卸载脚本内容, 使用root运行:

#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us 983708408@qq.com
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# Version v2.0
set -e

if [ "$USER" != "root" ]; then
  echo "Use the root user to execution this script!"
  exit 2
fi

MYSQL_BASE_DIR="$(cd "`dirname "$0"`"/..; pwd)"
cd $MYSQL_BASE_DIR


#
# Stopping of mysqld system service.
#
PIDS=`/bin/echo $(ps -ef|grep ${MYSQL_BASE_DIR}/bin/mysqld|grep -v grep|cut -c 9-15)`
if [ -n "$PIDS" ]; then
  while true
  do
    read -t 10 -p "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] MySQL Server on '${MYSQL_BASE_DIR}/bin/mysqld' is running, \
pids: '${PIDS}', [Danger]you must stop it first? (y|yes|n|no)" cover
    if [ -n "$(echo $cover|egrep -i 'Y|YES')" ]; then # Ignore case
      break;
    elif [ -n "$(echo $cover|egrep -i 'N|NO')" ]; then
      exit 0;
    else
      echo "Please reenter it!"
    fi
  done

  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Stopping MySQL Server on ${PIDS} ..."
  if [[ -f /etc/systemd/system/mysqld.service || -f /lib/systemd/system/mysqld.service ]]; then
    systemctl stop mysqld.service
  elif [ -f /etc/init.d/mysqld.service ]; then
    /etc/init.d/mysqld.service stop
  fi
fi


#
# Disable mysqld systemctl service.(if necessary)
#
if [ -f /etc/systemd/system/mysqld.service ]; then
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall MySQL System Service ..."
  sudo /bin/sh -c "exec systemctl disable mysqld"
fi


#
# Remove mysqld system service.
#
if [ -f /etc/systemd/system/mysqld.service ]; then # e.g: Ubuntu16.x+
  /bin/echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall Mysqld service of '/etc/systemd/system/mysqld.service' ..."
  /bin/rm -rf /etc/systemd/system/mysqld.service
elif [ -f /lib/systemd/system/mysqld.service ]; then # e.g: CenOS7.x, Ubuntu16.x
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall Mysqld service of '/lib/systemd/system/mysqld.service' ..."
  /bin/rm -rf /lib/systemd/system/mysqld.service
elif [ -f /etc/init.d/mysqld.service ]; then # CentOS6.x-
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall Mysqld service of '/etc/init.d/mysqld.service' ..."
  /bin/rm -rf /etc/init.d/mysqld.service
fi
# Generic
if [ -f /etc/systemd/system/multi-user.target.wants/mysqld.service ]; then
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall Mysqld service of '/etc/systemd/system/multi-user.target.wants/mysqld.service' ..."
  /bin/rm -rf /etc/systemd/system/multi-user.target.wants/mysqld.service
fi

#
# Cleanup server data files.
if [ -d "data/" ]; then
  while true
  do
    read -t 10 -p "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Do you need to remove the data directory on '${MYSQL_BASE_DIR}/data' \
to uninstall MySQL completely? It cannot be recovered after deletion. [Danger] Do you want to confirm deletion? (y|yes|n|no)" cover
    if [ -n "$(echo $cover|egrep -i 'Y|YES')" ]; then # Ignore case
      break;
    elif [ -n "$(echo $cover|egrep -i 'N|NO')" ]; then
      exit 0;
    else
      echo "Please reenter it!"
    fi
  done
  /bin/echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Force cleanup MySQL Server Data dir files ..."
  `/bin/rm -rf data/ conf/ run/ log/`
fi
# Fulsh systemd dbus. (if necessary)
if [ -f /bin/systemctl ]; then
  systemctl daemon-reload
fi


echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] UnInstall successfully!"

=======================================================================

=============若上面执行ok了, 本文后续的详细步骤也就可忽略了! ================

1.创建组及用户:
此步可以跳过,但是为了方便管理mysql,也为了用在正式的生产环境中,且处于安全考虑,这里为mysql单独建立了一个组及用户:

groupadd mysqlgroup  //新建一个mysqlgroup组
useradd -g mysqlgroup mysqluser  //创建一个名叫mysqluser的用户,将其归为mysqlgroup组

2.安装MySQL 5.7.17:
直接将下载的MySQL 5.7.17解压即可。

tar -xvzf mysql-5.7.17-linux-glibc2.5-x86_64.tar.gz

由于解压后的名字很长(mysql-5.7.17-linux-glibc2.5-x86_64),我们将它重命名为mysql,并将其移动到/usr/local 目录

mv mysql-5.7.17-linux-glibc2.5-x86_64 /usr/local/mysql

更改mysql目录下所有的目录及文件夹所属组合用户

chown -R mysqluser:mysqlgroup mysql //将mysql目录的所属权更改为mysqlgroup下的mysqluser用户
chmod -R 777 mysql  //赋予mysql目录读写权限

3.创建日志目录

mkdir /var/log/mysql
cd /var/log/mysql/
touch mysql.log
chmod -R 775 mysql.log
chown -R mysqluser:mysqlgroup mysql.log

4.初始化MySQL

cd /usr/local/mysql
./bin/mysqld --initialize --user=mysqluser --basedir=/usr/local/mysql

第一次初始化时,最后会显示这样的字样“A temporary password is generated for….”,显示root的临时密码。

5.启动数据库

./bin/mysqld_safe --user=mysqluser

6.1 【方案一】将mysqld服务加入开机自启动项
将{mysql}/ support-files/mysql.server 拷贝为/etc/init.d/mysql并设置运行权限,这样就可以使用service mysql命令启动/停止服务,
否则就只能使用{mysql}/bin/mysqld_safe &命令来启动服务
还需要把mysql.server中basedir的相关路径,改为自定义的路径,默认路径是/usr/local/mysql

[root@dbserver support-files]# cp mysql.server /etc/init.d/mysql  
[root@dbserver support-files]# chmod +x /etc/init.d/mysql 
-- 把mysql注册为开机启动的服务
[root@dbserver support-files]# chkconfig --add mysql  
-- 查看是否添加成功
[root@dbserver support-files]#  chkconfig --list mysql  
Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

mysql           0:off   1:off   2:on    3:on    4:on    5:on    6:off

6.2 【方案二】加入systemctl管理体系
以Ubuntu19为例:

vim /etc/systemd/system/mysql.service

service内容:

# MySQL5.7 systemd service.

[Unit]
Description=MySQL 5.7 Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=fork
User=mysql
Group=mysql
PIDFile=/run/mysql57.pid
PermissionsStartOnly=true
ExecStart=/bin/sh -c "exec /home/yourname/文档/software_install/mysql-5.7/bin/mysqld_safe"
ExecReload=/bin/kill -s HUP $MAINPID
# Will it cause 'Restart=on-abnormal' to be invalid?
#ExecStop=/bin/kill -s TERM $MAINPID
#StandardOutput=null
StandardError=journal
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=5
TimeoutSec=600
Restart=on-failure
RuntimeDirectoryMode=755

执行使用:

sudo systemctl daemon-reload
sudo systemctl start mysql
sudo systemctl status mysql  或  ps -ef|grep mysql
sudo systemctl enable mysql  # 加入开机自启

注: centos7路径是: vim /lib/systemd/system/mysql.service

7.启动服务

[root@dbserver bin]# service mysql start
  1. 登录mysql
[root@dbserver bin]# ./mysql -u root -p 密码
  1. 设置密码
set password for 'root'@'localhost' = password('123456');   //  Mysql5.7更改root密码的sql语句,123456是新的root密码(别忘了结尾的;号)
alter user 'root'@'localhost' identified with mysql_native_password by '123456';   //  Mysql8.0默认密码插件的名称已改为 mysql_native_password
  1. 设置远程登录权限
mysql>  grant all privileges on *.* to 'root' @'%' identified by 'root';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.06 sec)

mysql> quit
Bye

(第一个root表示用户名,%表示所有的电脑都可以连接,也可以设置某个ip地址运行连接,第二个root表示密码)。

  1. 开启防火墙端口 3306
# 3306端口放行
/sbin/iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
# 将该设置添加到防火墙的规则中
/etc/rc.d/init.d/iptables save

生产环境建议修改默认端口,vim /etc/mysql/my.cnf

  1. 验证启动参数
    如:验证bin log是否已成功开启

11.jpg

13, 解决Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’错误
mysql -u root -p -S /usr/local/mysql-8.0.20-linux-glibc2.12-x86_64/run/mysqld-wl4g_mysql.sock

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
2天前
|
Linux 开发工具 C语言
Linux 安装 gcc 编译运行 C程序
Linux 安装 gcc 编译运行 C程序
20 0
|
3天前
|
Ubuntu Linux Python
Linux(15)Ubuntu安装ninja构建工具
Linux(15)Ubuntu安装ninja构建工具
13 0
|
5天前
|
NoSQL Linux 测试技术
Redis的安装(Linux版)
Redis的安装(Linux版)
143 1
|
6天前
|
关系型数据库 MySQL 数据库
《MySQL 简易速速上手小册》第1章:MySQL 基础和安装(2024 最新版)
《MySQL 简易速速上手小册》第1章:MySQL 基础和安装(2024 最新版)
28 4
|
1天前
|
监控 安全 Linux
Linux系统之安装ServerBee服务器监控工具
【4月更文挑战第22天】Linux系统之安装ServerBee服务器监控工具
39 2
|
1天前
|
关系型数据库 MySQL Windows
windows安装MySQL5.7教程
windows安装MySQL5.7教程
8 0
|
1天前
|
SQL 存储 关系型数据库
MySQL Cluster集群安装及使用
MySQL Cluster集群安装及使用
|
2天前
|
Linux 开发工具 Android开发
Docker系列(1)安装Linux系统编译Android源码
Docker系列(1)安装Linux系统编译Android源码
4 0
|
2天前
|
Ubuntu Linux 开发工具
WSL2(3)安装Linux headers完美解决方案
WSL2(3)安装Linux headers完美解决方案
3 0
|
3天前
|
Ubuntu Linux 数据安全/隐私保护
Linux(7)Ubuntu20.04 arm64安装Docker
Linux(7)Ubuntu20.04 arm64安装Docker
14 0