PHP 在Linux/Unix(CentOS)上安装Web(Nginx)环境

  • 在Linux/Unix上安装

    如果您计划在Linux或任何其他Unix版本上安装PHP,那么这里是先决条件列表
    • PHP源代码分发https://www.php.net/downloads.php(PHP解析器)
    • 最新的Nginx源代码分发https://nginx.org/en/download.html(Web服务器)
    • 如果您打算使用一个支持PHP的数据库(例如MySQL,Oracle等) (数据服务器)
    • PHP如果连接的任何其他受支持的软件(邮件服务器,BCMath包,JDK等)(其他服务)
    • ANSI C编译器(编译上述软件的源码)
    • Gnu make utility - 您可以在https://www.gnu.org/software/make免费下载(安装上述软件)
  • 安装步骤

    本教程以Centos为例安装PHP+MySQL+Nginx三件套。
    步骤1 - 准备工作安装好下载工具和编译器
    用命令yum install -y wget 安装下载工具wget
    用命令yum install -y make 安装编译安装工具make
    用命令yum -y install wget cmake gcc gcc-c++ ncurses ncurses-devel libaio-devel openssl openssl-devel libxml2-devel MySQL安装编译工具及依赖工具
    用命令useradd mysql -f /sbin/nologin 添加mysql用户
    步骤2 - 下载源码包
    (1)下载PHP:
    $ wget http://www.php.net/distributions/php-7.3.8.tar.gz
    php linux
    (2)下载nginx:
    $ wget https://nginx.org/download/nginx-1.17.2.tar.gz
    php linux
    (3)下载MySQL(从国内的搜狐镜像下载,速度快):
    $ wget http://mirrors.sohu.com/mysql/MySQL-8.0/mysql-boost-8.0.11.tar.gz
    php linux
    步骤3 - 安装Mysql
    解压mysql源码包
    $ tar -zxvf mysql-boost-8.0.11.tar.gz
    进入源码包文件夹
    $ cd mysql-boost-8.0.11
    配置MySQL
    $ cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/local/mysql/data -DSYSCONFDIR=/etc -DMYSQL_TCP_PORT=3306  -DWITH_BOOST=/root/env/mysql-8.0.11/boost
    出现如下图示,配置成功
    php linux
    编译
    $ make
    php linux
    安装
    $ make install
    php linux
    初始化
    $ bin/mysqld --initialize --user=root --datadir=/data/mysql/
    php linux
    修改配置文件vi /etc/my.cnf>
    [mysqld]
    sql_mode=NO_ENGINE_SUBSTITUTION
    pid-file    = /tmp/mysqld.pid
    socket      = /tmp/mysql.sock
    datadir     = /data/mysql
    symbolic-links=0
    server-id = 11
    port = 3306
    user = mysql
    autocommit = 1
    character_set_server=utf8mb4
    skip_name_resolve = 1
    max_connections = 800
    max_connect_errors = 1000
    transaction_isolation = READ-COMMITTED
    join_buffer_size = 128M
    tmp_table_size = 64M
    tmpdir = /tmp
    max_allowed_packet = 256M
    interactive_timeout = 1200 
    wait_timeout = 600 
    read_buffer_size = 16M 
    read_rnd_buffer_size = 8M 
    sort_buffer_size = 8M 
    #表示记录下没有使用索引的查询
    log_queries_not_using_indexes = 1
    #记录管理语句
    log_slow_admin_statements = 1
    #开启复制从库复制的慢查询的日志
    log_slow_slave_statements = 1
    #设置每分钟增长的没有使用索引查询的日志数量
    log_throttle_queries_not_using_indexes = 10
    expire_logs_days = 90
    min_examined_row_limit = 100
    innodb_page_size = 16K
    #数据缓冲区buffer pool大小,建议使用物理内存的 75%
    innodb_buffer_pool_size = 2G
    #当buffer_pool的值较大的时候为1,较小的设置为8
    innodb_buffer_pool_instances = 8
    #运行时load缓冲池,快速预热缓冲池,将buffer pool的内容(文件页的索引)dump到文件中,然后快速load到buffer pool中。避免了数据库的预热过程,提高了应用访问的性能
    innodb_buffer_pool_load_at_startup = 1
    #运行时dump缓冲池
    innodb_buffer_pool_dump_at_shutdown = 1
    #在innodb中处理用户查询后,其结果在内存空间的缓冲池已经发生变化,但是还未记录到磁盘。这种页面称为脏页,将脏页记录到磁盘的过程称为刷脏
    innodb_lru_scan_depth = 2000
    innodb_io_capacity = 4000
    innodb_io_capacity_max = 8000
    #事务等待获取资源等待的最长时间,超过这个时间还未分配到资源则会返回应用失败,默认50s
    innodb_lock_wait_timeout = 30
    #日志组所在的路径,默认为data的home目录;
    innodb_log_group_home_dir = /data/mysql
    #innodb_undo_directory = /data/mysql/undolog/
    #这个参数控制着innodb数据文件及redo log的打开、刷写模式,http://blog.csdn.net/gua___gua/article/details/44916207
    #innodb_flush_method = O_DIRECT-不经过系统缓存直接存入磁盘,
    #innodb_file_format = Barracuda
    #innodb_file_format_max = Barracuda
    innodb_strict_mode = 1
    #innodb独享表空间,有点很多,缺点会导致单个表文件过大
    #innodb_file_per_table = 1
    #undo日志回滚段 默认为128
    #innodb_undo_logs = 128
    #传统机械硬盘建议使用,而对于固态硬盘可以关闭
    #innodb_flush_neighbors = 1
    innodb_log_file_size = 1G
    innodb_log_buffer_size = 64M
    #控制是否使用独立purge线程
    innodb_purge_threads = 1
    log_error = /var/log/mysql/error.log
    #开启慢查询日志
    slow_query_log = 1
    #超出次设定值的SQL即被记录到慢查询日志
    long_query_time = 6
    slow_query_log_file = /var/log/mysql/slow.log
    log_timestamps=system
    skip-grant-tables  #此项是为了装好后免登陆修改密码使用
    
    [mysql]
    socket      = /tmp/mysql.sock
    [client]
    socket      = /tmp/mysql.sock
    [mysqldump]
    socket      = /tmp/mysql.sock
    [mysqladmin]
    socket      = /tmp/mysql.sock
    
    错误日志文件夹,并授权文件夹
    $ mkdir -p /var/log/mysql
    $ chown mysql.mysql  /var/log/mysql
    $ chmod -R 755 /data/mysql
    $ chown -R mysql.mysql /data/mysql
    
    启动
    $ bin/mysqld --user=root &
    
    登录
    $ bin/mysql -u root -p
    
    密码输入步骤直接回车
    清空root密码
    mysql> use mysql;
    mysql> update user set authentication_string = '' where user = 'root';               
    
    然后退出删除(/etc/my.cnf)中skip-grant-tables这一行,重启mysqld服务,重新登录进入mysql
    mysql> exit;   #退出mysql
    $ ps aux | grep mysqld  #找出mysqld服务的pid
    $ kill -9 9130          #杀死mysqld进程 9130 是mysqld的正在运行的pid
    $ bin/mysqld --user=root &   #重新启动mysqld
    $ bin/mysql -u root -p   #连接mysql服务
    
    密码输入步骤直接回车(因为root密码被清空)
    修改密码
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MYtest123';
    修改登录IP限制,不修改就只能本地登录
    mysql> use mysql; 
    mysql> update user set host = '%' where user = 'root';               
    
    把mysqld服务加入到系统服务中管理vi /etc/rc.d/init.d/mysqld
    #!/bin/sh
    basedir=/usr/local/mysql
    datadir=/data/mysql
    service_startup_timeout=900
    lockdir='/var/lock/subsys'
    lock_file_path="$lockdir/mysql"
    if test -z "$basedir"
    then
      basedir=/usr/local/mysql
      bindir=/usr/local/mysql/bin
      if test -z "$datadir"
      then
        datadir=/data/mysql
      fi
      sbindir=/usr/local/mysql/bin
      libexecdir=/usr/local/mysql/bin
    else
      bindir="$basedir/bin"
      if test -z "$datadir"
      then
        datadir="$basedir/data"
      fi
      sbindir="$basedir/sbin"
      libexecdir="$basedir/libexec"
    fi
    datadir_set=
    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 "$bindir/my_print_defaults";  then
      print_defaults="$bindir/my_print_defaults"
    else
      # Try to find basedir in /etc/my.cnf
      conf=/etc/my.cnf
      print_defaults=
      if test -r $conf
      then
        subpat='^[^=]*basedir[^=]*=\(.*\)
    
    保存退出!加入系统服务chkconfig --add mysqld --level 235,此时可用命令service mysqld restart来重启mysqld服务。
    步骤4- 安装nginx
    解压tar -zxvf nginx-1.17.2.tar.gz
    进入源码文件夹cd nginx-1.17.2
    配置./configure --prefix=/usr/local/nginx
    编译make
    安装make install
    测试:在浏览器打开ip地址查看到如下,nginx安装成功
    php linux
    提示:如果不是在本机测试,请注意打开80端口的访问,或者关闭防火墙。
    加入系统服务vi /etc/rc.d/init.d/nginx
    #!/bin/sh
    #chkconfig:235 61 61
    #description:nginx
    
    . /etc/rc.d/init.d/functions
    
    . /etc/sysconfig/network
    
    
    [ "$NETWORKING" = "no" ] && exit 0
    
    nginx="/usr/local/nginx/sbin/nginx"
    
    prog=$(basename $nginx)
    
    NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
    
    lockfile=/var/lock/subsys/nginx
    
    start() {
    
        [ -x $nginx ] || exit 5
    
        [ -f $NGINX_CONF_FILE ] || exit 6
    
        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
    
        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
            
    
    加入服务chkconfig --add nginx --level 235
    重启nginxservice nginx restart
    步骤5- 安装PHP
    添加www用户useradd www -s /sbin/nologin
    解压缩包tar -zxvf php-7.3.8.tar.gz
    进入源码文件夹cd php-7.3.8
    配置./configure --prefix=/usr/local/php --enable-fpm --with-fpm-user=www --with-fpm-group=www
    编译make -j 4
    提示-j表示编译的时候同时有多少个工作进程在执行,一般设置为CPU核心数的两倍,本例的主机是双核,设置为4
    安装make install
    复制配置文件到PHP安装目录配置文件夹cp php.ini-development /usr/local/php/etc/php.ini
    删除系统自带的rm -f /etc/php.ini
    配置文件添加软链接ln -s /usr/local/php/etc/php.ini /etc/php.ini
    编辑配置文件,修改时区vi /etc/php.ini,找到如下图所示的代码,去掉前面分号,赋值PRC
    php linux
    复制启动文件到系统服务文件夹cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm
    赋予执行权限chmod +x /etc/rc.d/init.d/php-fpm
    添加到启动项chkconfig --add php-fpm --level 235
    开始配置nginx+PHP组合
    配置php-fpmcp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
    配置php-fpmvi /usr/local/php/etc/php-fpm.conf,找到如下图所示代码,去掉前面的分号,保存退出。
    php linux
    配置php-fpmcp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
    配置Nginx支持PHPvi /usr/local/nginx/conf/nginx.conf,如下图修改处修改。
    php linux
    php linux
    重启nginxservice nginx restart
    启动php-fpmservice php-fpm start
    测试php在web服务器(nginx)上的运行。
    编写测试脚本vi /usr/local/nginx/html/info.php,输入如下图代码,保存退出。
    php linux
    赋予执行权限chmod +x /usr/local/nginx/html/info.php
    在浏览器输入目标脚本地址,出现如下图示,说明PHP脚本已经正确运行在Nginx之上。
    php linux
    至此,PHP的Web运行环境,已经搭建完毕,后面会介绍到PHP跟数据库Mysql之间的协同工作的内容。