Linux安装LNMP

新装的系统更改下源吧
1、进入yum配置文件目录

yum install wget
cd /etc/yum.repos.d/

2、备份配置文件

mv CentOS-Base.repo CentOS-Base.repo.bak

3、下载163的配置
如果是7,那么

wget http://mirrors.163.com/.help/CentOS7-Base-163.repo #下载下来的文件名为 CentOS6-Base-163.repo
mv CentOS7-Base-163.repo CentOS-Base.repo

如果是6,那么

wget http://mirrors.163.com/.help/CentOS6-Base-163.repo #下载下来的文件名为 CentOS6-Base-163.repo
mv CentOS6-Base-163.repo CentOS-Base.repo

4、增加额外的源
如果是7,那么

wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

如果是6,那么

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -Uvh epel-release*rpm

5、更新数据库

yum update

一、安装编译必须先安装相应的编译工具

yum -y install gcc gcc-c++ autoconf automake libtool make
yum -y install zlib zlib-devel openssl openssl-devel
yum -y install libc-client-devel

建立nginx 组

groupadd -r www
useradd -s /sbin/nologin -g www -r www
id www

建立mysql组

groupadd mysql
mkdir -p /srv/mysql/data
useradd mysql -g mysql -d /opt/mysql
chown -R mysql.mysql /opt/mysql
chown -R mysql.mysql /srv/mysql

建立redis组

groupadd -r redis
useradd -s /sbin/nologin -g redis -r redis

二、下载,解压

mkdir /srv/build
cd /srv/build

PHP:

wget http://cn2.php.net/distributions/php-5.6.29.tar.gz
tar -zxvf php-5.6.29.tar.gz

MySQL(已编译):

wget http://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.16-linux-glibc2.5-x86_64.tar
tar -xvf mysql-5.7.16-linux-glibc2.5-x86_64.tar
tar -xzvf mysql-5.7.16-linux-glibc2.5-x86_64.tar.gz
mv mysql-5.7.16-linux-glibc2.5-x86_64/* /opt/mysql/

Nginx:

wget http://nginx.org/download/nginx-1.10.2.tar.gz
tar -xzvf nginx-1.10.2.tar.gz

三、安装或编译
PHP的依赖包

yum install libxml2-devel bzip2-devel curl-devel db4-devel libjpeg-devel libpng-devel libXpm-devel gmp-devel libc-client-devel l openldap-devel unixODBC-devel sqlite-devel aspell-devel net-snmp-devel libxslt-devel pcre-devel mysql-devel unixODBC-devel postgresql-devel pspell-devel net-snmp-devel libxslt-devel freetype-devel libvpx-devel ImageMagick-devel libtool-ltdl-devel
yum install libmcrypt-devel mhash-devel mcrypt enchant-devel libicu-devel freetds-devel readline-devel libtidy-devel systemd-devel

wget http://mirror.hust.edu.cn/gnu/libiconv/libiconv-1.14.tar.gz
tar xzvf libiconv-1.14.tar.gz
cd libiconv-1.14
cd srclib/
sed -i -e '/gets is a security/d' ./stdio.in.h
cd ../
./configure
make
make install
echo "/usr/local/lib" >> /etc/ld.so.conf.d/local.conf
ldconfig

wget https://nih.at/libzip/libzip-1.1.2.tar.gz
tar xzvf libzip-1.1.2.tar.gz
cd libzip-1.1.2
./configure
make
make install

wget ftp://ftp.freetds.org/pub/freetds/stable/freetds-patched.tar.gz
tar xzvf freetds-patched.tar.gz
cd freetds-1.00.23
./configure
make
make install

# 修复部分路径
cp -frp /usr/lib64/libldap* /usr/lib/
ln -s /usr/lib64/libsybdb.so.5.0.0 /usr/lib/libsybdb.so
ln -s /usr/lib64/libXpm.so* /usr/lib/
ln -s /usr/lib64/libc-client.so /usr/lib/libc-client.so
ln -vs /usr/local/lib/libzip/include/zipconf.h /usr/local/include
ln -s /usr/local/lib/libzip.so /usr/lib/libzip.so

如果是5.4的老版本需要增加:

yum -y install enchant-devel libXpm-devel freetds-devel libtidy-devel
cd ..
cd php-5.6.29
./configure \
--config-cache \
--prefix=/opt/php/usr \
--sysconfdir=/opt/php/etc \
--localstatedir=/opt/php/var \
--libdir=/opt/php/lib \
--datarootdir=/opt/php/usr/share \
--datadir=/opt/php/usr/share \
--with-layout=GNU \
--with-config-file-path=/opt/php/etc \
--with-config-file-scan-dir=/opt/php/etc/conf.d \
--disable-rpath \
--without-pear \
--enable-bcmath=shared \
--enable-calendar=shared \
--enable-dba=shared \
--enable-exif=shared \
--enable-ftp=shared \
--enable-gd-native-ttf \
--enable-intl=shared \
--enable-mbstring \
--enable-opcache \
--enable-phar=shared \
--enable-posix=shared \
--enable-shmop=shared \
--enable-soap=shared \
--enable-sockets=shared \
--enable-sysvmsg=shared \
--enable-sysvsem=shared \
--enable-sysvshm=shared \
--enable-zip=shared \
--with-bz2=shared \
--with-curl=shared \
--with-enchant=shared \
--with-freetype-dir \
--with-xpm-dir \
--with-gd=shared \
--with-gdbm \
--with-gettext=shared \
--with-gmp=shared \
--with-iconv-dir=/usr/local/lib \
--with-icu-dir=/usr \
--with-imap-ssl \
--with-imap=shared \
--with-kerberos \
--with-jpeg-dir \
--with-vpx-dir \
--with-ldap=shared \
--with-ldap-sasl \
--with-libzip \
--with-mcrypt=shared \
--with-mhash \
--with-mssql=shared \
--with-mysql-sock=/opt/mysql/mysqld.sock \
--with-mysql=shared,mysqlnd \
--with-mysqli=shared,mysqlnd \
--with-openssl=shared \
--with-pcre-regex \
--with-pdo-dblib=shared \
--with-pdo-mysql=shared,mysqlnd \
--with-pdo-odbc=shared,unixODBC,/usr \
--with-pdo-pgsql=shared \
--with-pdo-sqlite=shared \
--with-pgsql=shared \
--with-png-dir \
--with-pspell=shared \
--with-snmp=shared \
--with-sqlite3=shared \
--with-tidy=shared \
--with-unixODBC=shared,/usr \
--with-libxml-dir \
--with-xmlrpc=shared \
--enable-xmlreader \
--enable-xmlwriter \
--with-xsl=shared \
--with-zlib \
--enable-mbregex \
--enable-inline-optimization \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
# 这里仅仅支持centos7以上版本
--with-fpm-systemd

这里根据你的编译目标进行设置

PHP
--disable-cgi \
--with-readline \
--enable-pcntl \
CGI&FASTCGI
--program-suffix=-cgi \
--disable-cli \
--enable-cgi \
APACHE
--program-suffix=-apache24 \
--disable-cli \
--with-apxs2 \
PHP-FPM
#--program-suffix=-fpm \
--disable-cli \
--enable-fpm \
--with-fpm-systemd \
--with-fpm-user=www \
--with-fpm-group=www \
PHPDBG
--program-suffix=-dbg \
--disable-cli \
--disable-cgi \
--with-readline \
--enable-phpdbg \
PEAR
--disable-pear \
--with-readline \
--enable-pcntl \
--with-pear \

make
make install

如果提示undefined reference to ‘libiconv_open’
編輯 Makefile 大約 77 行左右的地方:

EXTRA_LIBS = ..... -lcrypt

在最後加上 -liconv,例如:

EXTRA_LIBS = ..... -lcrypt -liconv
cp php.ini-development /opt/php/etc/php.ini

Nginx的依赖关系:

yum install GeoIP-devel

cd ../

如果需要增加google反向代理功能
git clone https://github.com/cuber/ngx_http_google_filter_module
git clone https://github.com/yaoweibin/ngx_http_substitutions_filter_module

cd nginx-1.10.2
./configure \
--prefix=/opt/nginx \
--conf-path=/opt/nginx/etc/nginx/nginx.conf \
--sbin-path=/opt/nginx/usr/bin/nginx \
--pid-path=/opt/nginx/run/nginx.pid \
--lock-path=/opt/nginx/run/lock/nginx.lock \
--http-log-path=/opt/nginx/var/log/nginx/access.log \
--error-log-path=stderr \
--http-client-body-temp-path=/opt/nginx/var/lib/nginx/client-body \
--http-proxy-temp-path=/opt/nginx/var/lib/nginx/proxy \
--http-fastcgi-temp-path=/opt/nginx/var/lib/nginx/fastcgi \
--http-scgi-temp-path=/opt/nginx/var/lib/nginx/scgi \
--http-uwsgi-temp-path=/opt/nginx/var/lib/nginx/uwsgi \
--with-mail \
--with-mail_ssl_module \
--with-ipv6 \
--with-pcre-jit \
--with-file-aio \
--with-http_auth_request_module \
--with-http_geoip_module \
--with-http_dav_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_addition_module \
--with-http_degradation_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_secure_link_module \
--with-http_sub_module \
--with-http_v2_module \
--with-mail \
--with-mail_ssl_module \
--with-stream \
--with-stream_ssl_module \
--add-module=../ngx_http_google_filter_module \
--add-module=../ngx_http_substitutions_filter_module \
--with-threads
make
make install

关闭seLinux

nano -w /etc/selinux/config
SELINUX=enforcing改为SELINUX=disabled

四、PHP自动启动

#! /bin/sh

### BEGIN INIT INFO
# Provides:          php-fpm
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts php-fpm
# Description:       starts the PHP FastCGI Process Manager daemon
### END INIT INFO

prefix=/opt/php
exec_prefix=${prefix}

php_fpm_BIN=${exec_prefix}/usr/sbin/php-fpm
php_fpm_CONF=${prefix}/etc/php-fpm.conf
php_fpm_PID=${prefix}/var/run/php-fpm.pid

php_opts="--fpm-config $php_fpm_CONF --pid $php_fpm_PID"

wait_for_pid () {
        try=0
        while test $try -lt 35 ; do
                case "$1" in
                        'created')
                        if [ -f "$2" ] ; then
                                try=''
                                break
                        fi
                        ;;

                        'removed')
                        if [ ! -f "$2" ] ; then
                                try=''
                                break
                        fi
                        ;;
                esac

                echo -n .
                try=`expr $try + 1`
                sleep 1
        done
}

case "$1" in
        start)
                echo -n "Starting php-fpm "
                $php_fpm_BIN --daemonize $php_opts
                if [ "$?" != 0 ] ; then
                        echo " failed"
                        exit 1
                fi
                wait_for_pid created $php_fpm_PID
                if [ -n "$try" ] ; then
                        echo " failed"
                        exit 1
                else
                        echo " done"
                fi
        ;;

        stop)
                echo -n "Gracefully shutting down php-fpm "
                if [ ! -r $php_fpm_PID ] ; then
                        echo "warning, no pid file found - php-fpm is not running ?"
                        exit 1
                fi
                kill -QUIT `cat $php_fpm_PID`
                wait_for_pid removed $php_fpm_PID
                if [ -n "$try" ] ; then
                        echo " failed. Use force-quit"
                        exit 1
                else
                        echo " done"
                fi
        ;;

        status)
                if [ ! -r $php_fpm_PID ] ; then
                        echo "php-fpm is stopped"
                        exit 0
                fi
                PID=`cat $php_fpm_PID`
                if ps -p $PID | grep -q $PID; then
                        echo "php-fpm (pid $PID) is running..."
                else
                        echo "php-fpm dead but pid file exists"
                fi
        ;;

        force-quit)
                echo -n "Terminating php-fpm "
                if [ ! -r $php_fpm_PID ] ; then
                        echo "warning, no pid file found - php-fpm is not running ?"
                        exit 1
                fi
                kill -TERM `cat $php_fpm_PID`
                wait_for_pid removed $php_fpm_PID
                if [ -n "$try" ] ; then
                        echo " failed"
                        exit 1
                else
                        echo " done"
                fi
        ;;

        restart)
                $0 stop
                $0 start
        ;;

        reload)
                echo -n "Reload service php-fpm "
                if [ ! -r $php_fpm_PID ] ; then
                        echo "warning, no pid file found - php-fpm is not running ?"
                        exit 1
                fi
                kill -USR2 `cat $php_fpm_PID`
                echo " done"
        ;;

        *)
                echo "Usage: $0 {start|stop|force-quit|restart|reload|status}"
                exit 1
        ;;
esac

六、插件redis, memcache, phalcon, xcache, imagick

wget http://pecl.php.net/get/redis-2.2.8.tgz
tar xzvf redis-2.2.8.tgz
cd redis-2.2.8/
/opt/php/usr/bin/phpize
./configure --with-php-config=/opt/php/usr/bin/php-config
make
make install

cd ../
wget http://pecl.php.net/get/memcache-3.0.8.tgz
tar xzvf memcache-3.0.8.tgz
cd memcache-3.0.8/
/opt/php/usr/bin/phpize
./configure --with-php-config=/opt/php/usr/bin/php-config
make
make install

cd ../
wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz
tar xzvf xcache-3.2.0.tar.gz
cd xcache-3.2.0/
/opt/php/usr/bin/phpize
./configure --with-php-config=/opt/php/usr/bin/php-config
make
make install

cd ../
wget http://pecl.php.net/get/imagick-3.4.1.tgz
tar xzvf imagick-3.4.1.tgz
cd imagick-3.4.1/
/opt/php/usr/bin/phpize
./configure --with-php-config=/opt/php/usr/bin/php-config
make
make install

cd ../
export PATH=/opt/php/usr/bin:$PATH
git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build
./install

cd ../
wget https://xdebug.org/files/xdebug-2.5.0.tgz
tar xzvf xdebug-2.5.0.tgz
cd xdebug-2.5.0
/opt/php/usr/bin/phpize
./configure --enable-xdebug --with-php-config=/opt/php/usr/bin/php-config
make && make install

增加配置项到php.ini

[PHP]

;;;;;;;;;;;;;;;;;;;
; About php.ini   ;
;;;;;;;;;;;;;;;;;;;
; PHP's initialization file, generally called php.ini, is responsible for
; configuring many of the aspects of PHP's behavior.

; PHP attempts to find and load this configuration from a number of locations.
; The following is a summary of its search order:
; 1. SAPI module specific location.
; 2. The PHPRC environment variable. (As of PHP 5.2.0)
; 3. A number of predefined registry keys on Windows (As of PHP 5.2.0)
; 4. Current working directory (except CLI)
; 5. The web server's directory (for SAPI modules), or directory of PHP
; (otherwise in Windows)
; 6. The directory from the --with-config-file-path compile time option, or the
; Windows directory (C:\windows or C:\winnt)
; See the PHP docs for more specific information.
; http://php.net/configuration.file

; The syntax of the file is extremely simple.  Whitespace and lines
; beginning with a semicolon are silently ignored (as you probably guessed).
; Section headers (e.g. [Foo]) are also silently ignored, even though
; they might mean something in the future.

; Directives following the section heading [PATH=/www/mysite] only
; apply to PHP files in the /www/mysite directory.  Directives
; following the section heading [HOST=www.example.com] only apply to
; PHP files served from www.example.com.  Directives set in these
; special sections cannot be overridden by user-defined INI files or
; at runtime. Currently, [PATH=] and [HOST=] sections only work under
; CGI/FastCGI.
; http://php.net/ini.sections

; Directives are specified using the following syntax:
; directive = value
; Directive names are *case sensitive* - foo=bar is different from FOO=bar.
; Directives are variables used to configure PHP or PHP extensions.
; There is no name validation.  If PHP can't find an expected
; directive because it is not set or is mistyped, a default value will be used.

; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one
; of the INI constants (On, Off, True, False, Yes, No and None) or an expression
; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a
; previously set variable or directive (e.g. ${foo})

; Expressions in the INI file are limited to bitwise operators and parentheses:
; |  bitwise OR
; ^  bitwise XOR
; &  bitwise AND
; ~  bitwise NOT
; !  boolean NOT

; Boolean flags can be turned on using the values 1, On, True or Yes.
; They can be turned off using the values 0, Off, False or No.

; An empty string can be denoted by simply not writing anything after the equal
; sign, or by using the None keyword:

;  foo =         ; sets foo to an empty string
;  foo = None    ; sets foo to an empty string
;  foo = "None"  ; sets foo to the string 'None'

; If you use constants in your value, and these constants belong to a
; dynamically loaded extension (either a PHP extension or a Zend extension),
; you may only use these constants *after* the line that loads the extension.

;;;;;;;;;;;;;;;;;;;
; About this file ;
;;;;;;;;;;;;;;;;;;;
; PHP comes packaged with two INI files. One that is recommended to be used
; in production environments and one that is recommended to be used in
; development environments.

; php.ini-production contains settings which hold security, performance and
; best practices at its core. But please be aware, these settings may break
; compatibility with older or less security conscience applications. We
; recommending using the production ini in production and testing environments.

; php.ini-development is very similar to its production variant, except it is
; much more verbose when it comes to errors. We recommend using the
; development version only in development environments, as errors shown to
; application users can inadvertently leak otherwise secure information.

; This is php.ini-production INI file.

;;;;;;;;;;;;;;;;;;;
; Quick Reference ;
;;;;;;;;;;;;;;;;;;;
; The following are all the settings which are different in either the production
; or development versions of the INIs with respect to PHP's default behavior.
; Please see the actual settings later in the document for more details as to why
; we recommend these changes in PHP's behavior.

; display_errors
;   Default Value: On
;   Development Value: On
;   Production Value: Off

; display_startup_errors
;   Default Value: Off
;   Development Value: On
;   Production Value: Off

; error_reporting
;   Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
;   Development Value: E_ALL
;   Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

; html_errors
;   Default Value: On
;   Development Value: On
;   Production value: On

; log_errors
;   Default Value: Off
;   Development Value: On
;   Production Value: On

; max_input_time
;   Default Value: -1 (Unlimited)
;   Development Value: 60 (60 seconds)
;   Production Value: 60 (60 seconds)

; output_buffering
;   Default Value: Off
;   Development Value: 4096
;   Production Value: 4096

; register_argc_argv
;   Default Value: On
;   Development Value: Off
;   Production Value: Off

; request_order
;   Default Value: None
;   Development Value: "GP"
;   Production Value: "GP"

; session.gc_divisor
;   Default Value: 100
;   Development Value: 1000
;   Production Value: 1000

; session.hash_bits_per_character
;   Default Value: 4
;   Development Value: 5
;   Production Value: 5

; short_open_tag
;   Default Value: On
;   Development Value: Off
;   Production Value: Off

; track_errors
;   Default Value: Off
;   Development Value: On
;   Production Value: Off

; url_rewriter.tags
;   Default Value: "a=href,area=href,frame=src,form=,fieldset="
;   Development Value: "a=href,area=href,frame=src,input=src,form=fakeentry"
;   Production Value: "a=href,area=href,frame=src,input=src,form=fakeentry"

; variables_order
;   Default Value: "EGPCS"
;   Development Value: "GPCS"
;   Production Value: "GPCS"

;;;;;;;;;;;;;;;;;;;;
; php.ini Options  ;
;;;;;;;;;;;;;;;;;;;;
; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini"
;user_ini.filename = ".user.ini"

; To disable this feature set this option to empty value
;user_ini.filename =

; TTL for user-defined php.ini files (time-to-live) in seconds. Default is 300 seconds (5 minutes)
;user_ini.cache_ttl = 300

;;;;;;;;;;;;;;;;;;;;
; Language Options ;
;;;;;;;;;;;;;;;;;;;;

; Enable the PHP scripting language engine under Apache.
; http://php.net/engine
engine = On

; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It is
; generally recommended that  should be used and that this feature
; should be disabled, as enabling it may result in issues when generating XML
; documents, however this remains supported for backward compatibility reasons.
; Note that this directive does not control the 

七、MySQL编译安装

yum -y install cmake bison-devel  ncurses-devel
wget http://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.gz
tar xzvf boost_1_59_0.tar.gz
cd boost_1_59_0/
./bootstrap.sh
./b2 install

wget http://cdn.mysql.com//Downloads/MySQL-5.7/mysql-boost-5.7.13.tar.gz
tar xvf mysql-boost-5.7.13.tar.gz
cd mysql-5.7.13
cmake \
-DCMAKE_INSTALL_PREFIX=/opt/mysql \
-DMYSQL_DATADIR=/opt/mysql/data \
-DDOWNLOAD_BOOST=1 \
-DWITH_BOOST=../boost_1_59_0 \
-DSYSCONFDIR=/opt/mysql/etc \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_MEMORY_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITH_FEDERATED_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_READLINE=1 \
-DMYSQL_UNIX_ADDR=/opt/mysql/mysql.sock \
-DMYSQL_TCP_PORT=3306 \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \

下面是初始化

cp /opt/mysql/support-files/my-default.cnf /etc/my.cnf
cp /opt/mysql/support-files/mysql.server /etc/init.d/mysql
chmod 755 /etc/init.d/mysqld
chkconfig --level 345 mysqld on
/opt/mysql/bin/mysqld --initialize --user=mysql --basedir=/opt/mysql/ --datadir=/srv/mysql/data
#会显示临时密码
/opt/mysql/bin/mysql -u root -p
>SET PASSWORD = PASSWORD('');
>ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER;
>flush privileges;
MySQL8的加密方式发生了变更
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER; #修改加密规则 
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; #更新一下用户的密码 
FLUSH PRIVILEGES; #刷新权限 
再重置下密码:alter user 'root'@'localhost' identified by '123qwe';

注意:重点啊,如果你没有设置认证方式,默认的密码加密方式是:caching_sha2_password,而现在很多客户端工具还不支持这种加密认证方式,连接测试的时候就会报错:client does not support  authentication protocol requested by server; consider upgrading MySQL client,这里的错误信息就是不支持身份认证方式,没关系,去my.ini里面在[mysqld]下面加上这句话即可:

default_authentication_plugin=mysql_native_password

八、MySQL自动启动

#!/bin/sh
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind

# MySQL daemon start/stop script.

# Usually this is put in /etc/init.d (at least on machines SYSV R4 based
# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
# When this is done the mysql server will be started when the machine is
# started and shut down when the systems goes down.

# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 64 36
# description: A very fast and reliable SQL database engine.

# Comments to support LSB init script conventions
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $local_fs $network $remote_fs
# Should-Start: ypbind nscd ldap ntpd xntpd
# Required-Stop: $local_fs $network $remote_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop MySQL
# Description: MySQL is a very fast and reliable SQL database engine.
### END INIT INFO
 
# If you install MySQL on some other places than /opt/mysql, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/my.cnf file with the following information:
#   [mysqld]
#   basedir=
# - Add the above to any other configuration file (for example ~/.my.ini)
#   and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#   below.
#
# If you want to affect other MySQL variables, you should make your changes
# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.

# If you change base dir, you must also change datadir. These may get
# overwritten by settings in the MySQL configuration files.

basedir=
datadir=

# 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=/opt/mysql
  bindir=/opt/mysql/bin
  if test -z "$datadir"
  then
    datadir=/opt/mysql/data
  fi
  sbindir=/opt/mysql/bin
  libexecdir=/opt/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=`echo "$arg" | sed -e 's/^[^=]*=//'`
                    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 ./bin/my_print_defaults
then
  print_defaults="./bin/my_print_defaults"
elif test -x $bindir/my_print_defaults
then
  print_defaults="$bindir/my_print_defaults"
elif test -x $bindir/mysql_print_defaults
then
  print_defaults="$bindir/mysql_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
      if test -x "$d/bin/mysql_print_defaults"
      then
        print_defaults="$d/bin/mysql_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"
else
  if test -r "$datadir/my.cnf"
  then
    extra_args="-e $datadir/my.cnf"
  fi
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 --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null 2>&1 &
      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

这里是普通启动文件下载(普通启动,当然也能用在CentOS7上做普通启动)
init
这里是systemd启动文件下载(Systemd启动,仅仅适用Centos7)
systemd

关于Zeno Chen

本人涉及的领域较多,杂而不精 程序设计语言: Perl, Java, PHP, Python; 数据库系统: MySQL,Oracle; 偶尔做做电路板的开发,主攻STM32单片机
此条目发表在Linux分类目录。将固定链接加入收藏夹。