当前位置: 首页 > Web与应用 > 正文

CentOS 7 编译安装 Nginx + PHP + MySQL
Debian / Ubuntu 编译安装 Nginx + PHP + MySQL
Nginx版本:1.17.3
PHP版本:7.2.21 + OPCache
MySQL版本:5.6.45

 

CentOS更新系统软件包到最新

yum update

Debian/Ubuntu更新系统软件包到最新

apt-get update
apt-get -y upgrade

 

下载软件包到/tmp/lnmp目录

mkdir -p /tmp/lnmp
cd /tmp/lnmp
wget http://mirrors.sohu.com/nginx/nginx-1.17.3.tar.gz
wget http://mirrors.sohu.com/php/php-7.2.21.tar.gz
wget http://mirrors.163.com/mysql/Downloads/MySQL-5.6/mysql-5.6.45.tar.gz
wget https://files1.ich8.com/upfiles/2019/openssl-1.1.1c.tar.gz
wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz
wget https://www.zlib.net/zlib-1.2.11.tar.gz
#PHP探针
wget https://files1.ich8.com/upfiles/2019/tz.zip

CentOS 安装必要的软件包

yum -y install libxml2 libxml2-devel openssl openssl-devel curl-devel libjpeg-devel libpng-devel freetype-devel libmcrypt-devel mhash gd gd-devel autoconf cmake bison lrzsz gcc-c++ ncurses-devel automake libevent libevent-devel gd gd-devel libtool* libmcrypt libmcrypt-devel mcrypt mhash libxslt libxslt-devel readline readline-devel gmp gmp-devel libcurl libcurl-devel openjpeg-devel automake boost-devel glib2-devel gmp-devel jemalloc-devel libevent libevent-devel libicu-devel libidn-devel libtool libtool-ltdl libtool-ltdl-devel libxslt libxslt-devel mcrypt nss-pam-ldapd openjpeg-devel openldap-devel readline-devel

Debian/Ubuntu 安装必要的软件包

apt-get install -y autoconf cmake openssl libwrap0-dev libncurses5-dev libssl-dev libxml2-dev libcurl4-openssl-dev pkg-config libbz2-dev libjpeg-dev libxpm-dev libfreetype6-dev libmcrypt-dev libxslt1-dev libiconv-hook-dev libpcre3 libpcre3-dev gcc bison g++ lrzsz libperl-dev
apt-get install -y sysv-rc-conf  # 启动项管理

 

编译MySQL

# 进入lnmp目录
cd /tmp/lnmp

# 创建MySQL用户组和用户,不创建用户家目录,允许bash登陆
groupadd mysql
useradd -s /sbin/nologin -M -g mysql mysql

# 创建MySQL目录和数据库目录
mkdir -p /usr/local/mysql
mkdir -p /usr/local/mysql/data

# 赋予所有文件和子目录对应MySQL用户和组权限
chown -R mysql:mysql /usr/local/mysql

解压MySQL压缩包文件并编译安装

tar zxvf mysql-5.6.45.tar.gz
cd mysql-5.6.45
cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DSYSCONFDIR=/etc \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITH_FEDERATED_STORAGE_ENGINE=1 \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8mb4 \
-DDEFAULT_COLLATION=utf8mb4_general_ci \
-DWITH_EMBEDDED_SERVER=1 \
-DENABLED_LOCAL_INFILE=1 
make
make install

创建MySQL配置文件,位于etc目录下

cat > /etc/my.cnf<<EOF
[client]
#password	= your_password
port		= 3306
socket		= /tmp/mysql.sock

[mysqld]
port		= 3306
socket		= /tmp/mysql.sock
datadir = /usr/local/mysql/data
skip-external-locking
key_buffer_size = 16M
max_allowed_packet = 1M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
thread_cache_size = 8
query_cache_size = 8M
tmp_table_size = 16M

#skip-networking
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id	= 1
expire_logs_days = 10

default_storage_engine = InnoDB
innodb_data_home_dir = /usr/local/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /usr/local/mysql/data
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout


EOF

初始化MySQL数据库

cd /usr/local/mysql/
./scripts/mysql_install_db --defaults-file=/etc/my.cnf --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql

CentOS 创建启动脚本并设置开机自动启动

cp ./support-files/mysql.server /etc/init.d/mysql
chmod 755 /etc/init.d/mysql
chkconfig --add mysql

Debian/Ubuntu创建启动脚本并设置开机自动启动

cp ./support-files/mysql.server /etc/init.d/mysql
chmod 755 /etc/init.d/mysql
sysv-rc-conf mysql on
systemctl enable mysql.service

启动MySQL

service mysql start

修改默认root密码(默认为空)为123456

/usr/local/mysql/bin/mysqladmin -u root password '123456'

创建动态链接库文件

cat > /etc/ld.so.conf.d/mysql.conf<<EOF
    /usr/local/mysql/lib
    /usr/local/lib
EOF

ldconfig
ln -sf /usr/local/mysql/lib/mysql /usr/lib/mysql
ln -sf /usr/local/mysql/include/mysql /usr/include/mysql

 

编译PHP,创建www用户组和用户

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

解压php安装包并编译安装,需要搭配安装或开启的组件自行增删

cd /tmp/lnmp
tar zxvf php-7.2.21.tar.gz
cd php-7.2.21
./configure \
--prefix=/usr/local/php \
--with-config-file-path=/usr/local/php/etc \
--with-config-file-scan-dir=/usr/local/php/conf.d \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
--enable-mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--enable-mysqlnd-compression-support \
--with-iconv-dir \
--with-freetype-dir=/usr/local/freetype \
--with-jpeg-dir \
--with-png-dir \
--with-zlib \
--with-libxml-dir=/usr \
--with-curl \
--with-libmbfl \
--with-openssl \
--enable-xml \
--disable-rpath \
--enable-bcmath \
--enable-shmop \
--enable-sysvsem \
--enable-inline-optimization \
--enable-mbregex \
--enable-mbstring \
--enable-intl \
--enable-pcntl \
--enable-ftp \
--with-gd \
--with-mhash \
--enable-pcntl \
--enable-sockets \
--with-xmlrpc \
--enable-zip \
--enable-soap \
--with-gettext \
--enable-opcache \
--with-xsl
make
make install

创建php/etc和php/conf.d目录

mkdir -p /usr/local/php/etc
mkdir -p /usr/local/php/conf.d

复制php生产环境配置文件到php/etc目录并重命名为php.ini

cp php.ini-production /usr/local/php/etc/php.ini

修改php.ini配置文件,可自行vi手动修改

post_max_size  POST最大大小

upload_max_filesize  上传文件最大大小

date.timezone  时区

short_open_tag  是否允许代码标志的缩写标志

cgi.fix_pathinfo  CGI完整路径

max_execution_time  PHP超时设置

disable_functions  禁用函数

expose_php  不显示php版本信息

memory_limit  运行内存大小设置

sed -i 's/post_max_size =.*/post_max_size = 64M/g' /usr/local/php/etc/php.ini
sed -i 's/upload_max_filesize =.*/upload_max_filesize = 64M/g' /usr/local/php/etc/php.ini
sed -i 's/;date.timezone =.*/date.timezone = PRC/g' /usr/local/php/etc/php.ini
sed -i 's/short_open_tag =.*/short_open_tag = On/g' /usr/local/php/etc/php.ini
sed -i 's/;cgi.fix_pathinfo=.*/cgi.fix_pathinfo=1/g' /usr/local/php/etc/php.ini
sed -i 's/max_execution_time =.*/max_execution_time = 60/g' /usr/local/php/etc/php.ini
sed -i 's/disable_functions =.*/disable_functions = passthru,exec,system,chroot,chgrp,chown,shell_exec,proc_open,proc_get_status,popen,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server/g' /usr/local/php/etc/php.ini
sed -i 's/expose_php =.*/expose_php = Off/g' /usr/local/php/etc/php.ini
sed -i 's/memory_limit =.*/memory_limit = 256M/g' /usr/local/php/etc/php.ini

开启OPCache支持,提高php运行效率,在php.ini文件末尾
参数详解:https://www.php.net/manual/zh/opcache.configuration.php

cat >> /usr/local/php/etc/php.ini<<EOF

[opcache]
zend_extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20170718/opcache.so
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=192
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=5000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

EOF

创建php-fpm.conf文件

vi /usr/local/php/etc/php-fpm.conf

参数详解:https://www.php.net/manual/zh/install.fpm.configuration.php

[global]
pid = /usr/local/php/var/run/php-fpm.pid
error_log = /usr/local/php/var/log/php-fpm.log
log_level = notice

[www]
listen = /tmp/php-cgi.sock
listen.backlog = -1
listen.allowed_clients = 127.0.0.1
listen.owner = www
listen.group = www
listen.mode = 0666
user = www
group = www
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 6
pm.max_requests = 1024
pm.process_idle_timeout = 10s
request_terminate_timeout = 100
request_slowlog_timeout = 0
slowlog = var/log/slow.log

CentOS 创建php-fpm.service文件

vi /usr/lib/systemd/system/php-fpm.service

Ubuntu 创建php-fpm.service文件

mkdir -p /usr/lib/systemd/system
vi /usr/lib/systemd/system/php-fpm.service

php-fpm.service文件内容

[Unit]
Description=The PHP FastCGI Process Manager
After=syslog.target network.target

[Service]
Type=simple
PIDFile=/usr/local/php/var/run/php-fpm.pid
ExecStart=/usr/local/php/sbin/php-fpm --nodaemonize --fpm-config /usr/local/php/etc/php-fpm.conf
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target

创建软链接

ln -sf /usr/local/php/bin/php /usr/bin/php
ln -sf /usr/local/php/bin/phpize /usr/bin/phpize
ln -sf /usr/local/php/bin/pear /usr/bin/pear
ln -sf /usr/local/php/bin/pecl /usr/bin/pecl
ln -sf /usr/local/php/sbin/php-fpm /usr/bin/php-fpm

使能并自动启动php-fpm服务

systemctl enable php-fpm.service

重启php-fpm服务

systemctl restart php-fpm.service

 

解压Nginx安装文件以及自定义OpenSSL、PCRE、Zlib库源码包

cd /tmp/lnmp
tar zxvf  nginx-1.17.3.tar.gz
tar zxvf  openssl-1.1.1c.tar.gz
tar zxvf  pcre-8.43.tar.gz
tar zxvf  zlib-1.2.11.tar.gz

CentOS 安装perl模块,这里启用了Nginx的http_perl_module支持

yum -y install perl-devel perl-ExtUtils-Embed

编译并安装Nginx

cd nginx-1.17.3
./configure \
--user=www \
--group=www \
--prefix=/usr/local/nginx \
--with-openssl=../openssl-1.1.1c \
--with-pcre=../pcre-8.43 \
--with-pcre-jit \
--with-zlib=../zlib-1.2.11 \
--with-compat \
--with-file-aio \
--with-threads \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-ipv6 \
--with-http_sub_module \
--with-http_v2_module \
--with-http_perl_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
make
make install

建立软链接

ln -sf /usr/local/nginx/sbin/nginx /usr/bin/nginx

添加Nginx为系统服务,建立/etc/init.d/nginx文件

vi /etc/init.d/nginx

CentOS 适用的 /etc/init.d/nginx 文件内容

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /usr/local/nginx/conf/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /usr/local/nginx/logs/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload() {
    restart
}
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
    status $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

Debian/Ubuntu 适用的 /etc/init.d/nginx 文件内容

#! /bin/sh
# chkconfig: 2345 55 25
# Description: Startup script for nginx webserver on Debian. Place in /etc/init.d and
# run 'update-rc.d -f nginx defaults', or use the appropriate command on your
# distro. For CentOS/Redhat run: 'chkconfig --add nginx'

### BEGIN INIT INFO
# Provides:          nginx
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the nginx web server
# Description:       starts nginx using start-stop-daemon
### END INIT INFO

# Author:   licess
# website:  http://lnmp.org

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=nginx
NGINX_BIN=/usr/local/nginx/sbin/nginx
CONFIGFILE=/usr/local/nginx/conf/nginx.conf
PIDFILE=/usr/local/nginx/logs/nginx.pid

case "$1" in

start)
    echo -n "Starting $NAME... "

    if netstat -tnpl | grep -q nginx;then
        echo "$NAME (pid `pidof $NAME`) already running."
        exit 1
    fi

    $NGINX_BIN -c $CONFIGFILE

    if [ "$?" != 0 ] ; then
        echo " failed"
        exit 1
    else
        echo " done"
    fi
    ;;

stop)
    echo -n "Stoping $NAME... "

    if ! netstat -tnpl | grep -q nginx; then
        echo "$NAME is not running."
        exit 1
    fi

    $NGINX_BIN -s stop

    if [ "$?" != 0 ] ; then
        echo " failed. Use force-quit"
        exit 1
    else
        echo " done"
    fi
    ;;

status)
    if netstat -tnpl | grep -q nginx; then
        PID=`pidof nginx`
        echo "$NAME (pid $PID) is running..."
    else
        echo "$NAME is stopped"
        exit 0
    fi
    ;;

force-quit)
    echo -n "Terminating $NAME... "

    if ! netstat -tnpl | grep -q nginx; then
        echo "$NAME is not running."
        exit 1
    fi

    kill `pidof $NAME`

    if [ "$?" != 0 ] ; then
        echo " failed"
        exit 1
    else
        echo " done"
    fi
    ;;

restart)
    $0 stop
    sleep 1
    $0 start
    ;;

reload)
    echo -n "Reload service $NAME... "

    if netstat -tnpl | grep -q nginx; then
        $NGINX_BIN -s reload
        echo " done"
    else
        echo "$NAME is not running, can't reload."
        exit 1
    fi
    ;;

configtest)
    echo -n "Test $NAME configure files... "

    $NGINX_BIN -t
    ;;

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

esac

赋予所有用户组执行Nginx权限

chmod a+x /etc/init.d/nginx

CentOS 添加到开机启动并设置为开机自动启动

chkconfig --add /etc/init.d/nginx
chkconfig nginx on

Debian/Ubuntu 添加到开机启动并设置为开机自动启动

sysv-rc-conf nginx on

CentOS 启动Nginx服务

systemctl start nginx

Debian/Ubuntu 启动Nginx服务

systemctl enable nginx.service
systemctl start nginx

 

创建网站目录,添加网站以及日志目录并赋予对应的权限,网站目录赋予www用户组权限

这里添加2个网站 一个默认localhost或者IP地址打开,另外一个则要用域名才能打开

mkdir -p /data/web/wwwroot
mkdir -p /data/web/default
chmod 777 /data/web/wwwroot
chmod 777 /data/web/default
chown -R www:www /data/web/wwwroot
chown -R www:www /data/web/default

mkdir -p /data/web/wwwlogs
chmod 777 /data/web/wwwlogs

删除默认的Nginx配置文件,并在conf目录下创建vhost目录,用于存放网站的配置文件

rm -f /usr/local/nginx/conf/nginx.conf
mkdir -p /usr/local/nginx/conf/vhost

创建FastCGI PHP的加载文件(把配置文件分割成不同小份,方便维护)

vi /usr/local/nginx/conf/enable_php.conf
        location ~ [^/]\.php(/|$)
        {
            try_files $uri =404;
            fastcgi_pass  unix:/tmp/php-cgi.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
        }

创建nginx.conf主配置文件

vi /usr/local/nginx/conf/nginx.conf
user  www www;

worker_processes auto;

error_log  /data/web/wwwlogs/nginx_error.log  crit;

pid        /usr/local/nginx/logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
    {
        use epoll;
        worker_connections 51200;
        multi_accept on;
    }

http
    {
        include       mime.types;
        default_type  application/octet-stream;

        server_names_hash_bucket_size 128;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;

        sendfile   on;
        tcp_nopush on;

        keepalive_timeout 60;

        tcp_nodelay on;

        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;

        gzip on;
        gzip_min_length  1k;
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
        gzip_disable   "MSIE [1-6]\.";

        #limit_conn_zone $binary_remote_addr zone=perip:10m;
        ##If enable limit_conn_zone,add "limit_conn perip 10;" to server section.

        server_tokens off;
        access_log off;

server
    {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name localhost;
        index index.html index.htm index.php;
        root  /data/web/default;

        #error_page   404   /404.html;
        include enable_php.conf;

        location /nginx_status
        {
            stub_status on;
            access_log   off;
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|js|css)$
        {
            expires      7d;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log off;
    }
include vhost/*.conf;
}

创建网站的配置文件,网站存放目录为/data/web/wwwroot

vi /usr/local/nginx/conf/vhost/www.abc.com.conf

listen使用80端口,server_name 绑定的域名 root 网站目录。其他参数可参考官方wiki

server
    {
        listen 80;
        #listen [::]:80;
        server_name www.abc.com;
        index index.html index.htm index.php;
        root  /data/web/wwwroot;

        #include none.conf;
        #error_page   404   /404.html;
        location ~ [^/]\.php(/|$)
        {
            # comment try_files $uri =404; to enable pathinfo
            try_files $uri =404;
            fastcgi_pass  unix:/tmp/php-cgi.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|js|css)$
        {
            expires      7d;
        }

        access_log off;
    }

解压PHP探针到新建网站的目录

unzip /tmp/lnmp/tz.zip -d /data/web/wwwroot

检查Nginx配置是否有出错,提示测试successful即可。

nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重启php-fpm服务

systemctl restart php-fpm.service

平滑变更Nginx设置

nginx -s reload

其他

[分享]CentOS 7 /Debian / Ubuntu 编译安装 Nginx + PHP + MySQL:等您坐沙发呢!

发表评论