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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 干过几年的行内人几乎够碰到过,要在客户的非干净的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

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
12天前
|
存储 安全 数据管理
如何在 Rocky Linux 8 上安装和配置 Elasticsearch
本文详细介绍了在 Rocky Linux 8 上安装和配置 Elasticsearch 的步骤,包括添加仓库、安装 Elasticsearch、配置文件修改、设置内存和文件描述符、启动和验证 Elasticsearch,以及常见问题的解决方法。通过这些步骤,你可以快速搭建起这个强大的分布式搜索和分析引擎。
29 5
|
12天前
|
关系型数据库 MySQL Linux
Linux环境下MySQL数据库自动定时备份实践
数据库备份是确保数据安全的重要措施。在Linux环境下,实现MySQL数据库的自动定时备份可以通过多种方式完成。本文将介绍如何使用`cron`定时任务和`mysqldump`工具来实现MySQL数据库的每日自动备份。
31 3
|
12天前
|
监控 关系型数据库 MySQL
Linux环境下MySQL数据库自动定时备份策略
在Linux环境下,MySQL数据库的自动定时备份是确保数据安全和可靠性的重要措施。通过设置定时任务,我们可以每天自动执行数据库备份,从而减少人为错误和提高数据恢复的效率。本文将详细介绍如何在Linux下实现MySQL数据库的自动定时备份。
26 3
|
13天前
|
SQL 关系型数据库 MySQL
go语言数据库中mysql驱动安装
【11月更文挑战第2天】
29 4
|
19天前
|
关系型数据库 MySQL Linux
在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,并与使用 RPM 包安装进行了对比
本文介绍了在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,并与使用 RPM 包安装进行了对比。通过具体案例,读者可以了解如何准备环境、下载源码、编译安装、配置服务及登录 MySQL。编译源码安装虽然复杂,但提供了更高的定制性和灵活性,适用于需要高度定制的场景。
56 3
|
20天前
|
关系型数据库 MySQL Linux
在 CentOS 7 中通过编译源码安装 MySQL 数据库的详细步骤,并与使用 RPM 包安装进行了对比。
本文介绍了在 CentOS 7 中通过编译源码安装 MySQL 数据库的详细步骤,并与使用 RPM 包安装进行了对比。内容涵盖准备工作、下载源码、编译安装、配置服务、登录设置及实践心得,帮助读者根据需求选择最适合的安装方法。
36 2
|
8天前
|
运维 关系型数据库 MySQL
安装MySQL8数据库
本文介绍了MySQL的不同版本及其特点,并详细描述了如何通过Yum源安装MySQL 8.4社区版,包括配置Yum源、安装MySQL、启动服务、设置开机自启动、修改root用户密码以及设置远程登录等步骤。最后还提供了测试连接的方法。适用于初学者和运维人员。
66 0
|
8天前
|
存储 缓存 Linux
【Linux】另一种基于rpm安装yum的方式
通过本文的方法,您可以在离线环境中使用RPM包安装YUM并进行必要的配置。这种方法适用于无法直接访问互联网的服务器或需要严格控制软件源的环境。通过配置本地YUM仓库,确保了软件包的安装和更新可以顺利进行。希望本文能够为您在特定环境中部署YUM提供实用的指导。
59 0
|
14天前
|
关系型数据库 MySQL Linux
Linux-安装Mariadb
本文介绍了在 Alibaba Cloud Linux 系统上安装和配置 MariaDB 10.5 的步骤。包括下载安装、初始化数据库、启动服务、处理启动失败的常见问题(如权限问题),以及如何连接数据库、设置密码和允许外部连接。通过这些步骤,您可以顺利完成 MariaDB 的安装和基本配置。
29 0
|
7天前
|
监控 Linux
如何检查 Linux 内存使用量是否耗尽?这 5 个命令堪称绝了!
本文介绍了在Linux系统中检查内存使用情况的5个常用命令:`free`、`top`、`vmstat`、`pidstat` 和 `/proc/meminfo` 文件,帮助用户准确监控内存状态,确保系统稳定运行。
67 6
下一篇
无影云桌面