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

本文我在其他平台(https://gitee.com/wl4g-private/xcloud-blogs)的发布

工作几年的都碰到过吧,要在客户的不干净的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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,100评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,862评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,993评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,309评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,303评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,421评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,830评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,501评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,689评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,506评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,564评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,286评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,826评论 3 305
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,875评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,114评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,705评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,269评论 2 341

推荐阅读更多精彩内容