LNMP环境搭建

系统环境

Linux操作系统:Amazon linux(centos 6.5)
Nginx:nginx-1.8.1.tar.gz
Mysql:mysql-5.6.30.tar.gz
PHP:php-5.6.20.tar.gz
PCRE:yum安装

所需软件官方下载地址:

Nginx下载地址:http://nginx.org/download/nginx-1.8.1.tar.gz
Mysql下载地址:http://120.52.72.21/cdn.mysql.com/c3pr90ntc0td/archives/mysql-5.6/mysql-5.6.30.tar.gz
PHP下载地址:http://cn2.php.net/distributions/php-5.5.20.tar.gzz

一、 安装开发包环境:

# yum -y install wget gcc-c++ ncurses ncurses-devel cmake make perl bison openssl openssl-devel gcc* libxml2 libxml2-devel curl-devel libjpeg* libpng* freetype*

二、 关闭iptables和Selinux(生产环境中建议开启iptables):

Service iptables stop
Setenforce 0       #临时关闭Selinux

永久关闭selinx:

# vi /etct/sysconfig/selinux 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX= enforcing
#enforcing
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

修改红色字体为disabled然后保存:

   # This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
#enforcing
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

三、 编译安装mysql数据库:

  1. 安装前的初始配置工作:
    # useradd -d /usr/local/mysql/ mysql #创建一个mysql用户,指定家目录到/usr/local/mysql/
    # mkdir /usr/local/mysql/data #创建mysql数据目录
    # mkdir /usr/local/mysql/log #创建mysql日志目录
    # chown -R mysql:mysql /usr/local/mysql/data #修改data目录所有者和所属组
    # chown -R mysql:mysql /usr/local/mysql/log #修改log目录所有者和所属组
    # chmod 750 /usr/local/mysql/data #修改data目录访问权限
    # chmod 750 /usr/local/mysql/log #修改log目录访问权限
  2. 解压编译安装mysql:
    # tar zxvf mysql-5.6.30.tar.gz #解压mysql压缩包
    # cd mysql-5.6.30 #进入到mysql解压包目录
  3. 开始编译mysql:
    # cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql
    -DMYSQL_UNIX_ADDR=/tmp/mysql.sock
    -DDEFAULT_CHARSET=utf8
    -DDEFAULT_COLLATION=utf8_general_ci
    -DEXTRA_CHARSETS=all
    -DWITH_MYISAM_STORAGE_ENGINE=1
    -DWITH_INNOBASE_STORAGE_ENGINE=1
    -DWITH_ARCHIVE_STORAGE_ENGINE=1
    -DWITH_BLACKHOLE_STORAGE_ENGINE=1
    -DWITH_MEMORY_STORAGE_ENGINE=1
    -DWITH_FEDERATED_STORAGE_ENGINE=1
    -DWITH_READLINE=1
    -DENABLED_LOCAL_INFILE=1
    -DMYSQL_DATADIR=/usr/local/mysql/data
    -DMYSQL_PROJECT_NAME=mysql
    -DMYSQL_TCP_PORT=3306
    -DSYSCONFDIR=/etc
    -DWITH_SSL=yes
    # make && make install

编译解释:
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \ #指定安装目录
-DMYSQL_UNIX_ADDR=/tmp/mysql.sock \ #指定Unix socket文件路劲
-DDEFAULT_CHARSET=utf8 \ #指定默认字符
-DDEFAULT_COLLATION=utf8_general_ci \ #效验字符
-DEXTRA_CHARSETS=all \
-DWITH_MYISAM_STORAGE_ENGINE=1 \ #安装myisam
-DWITH_INNOBASE_STORAGE_ENGINE=1 \ #安装innodb存储引擎
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \ #安装archive存储引擎
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \ #安装blackhole存储引擎
-DWITH_MEMORY_STORAGE_ENGINE=1 \ #安装memory存储引擎
-DWITH_FEDERATED_STORAGE_ENGINE=1 \ #安装frderated存储引擎
-DWITH_READLINE=1 \ #快捷键功能
-DENABLED_LOCAL_INFILE=1 \ #允许从本地导入数据
-DMYSQL_DATADIR=/usr/local/mysql/data \ #数据库存放目录
-DMYSQL_USER=mysql \ #数据库属主
-DMYSQL_TCP_PORT=3306 \ #数据库端口
-DSYSCONFDIR=/etc \ #MySQL配辑文件
-DWITH_SSL=yes #数据库SSL

  1. 修改mysql配置文件:
    # vi /etc/my.cnf

      [mysql]
     # CLIENT #
     port                           = 3306
     socket                         = /tmp/mysql.sock
     
     [mysqld]
     # GENERAL #
     user                           = mysql
     default_storage_engine         = InnoDB
     socket                         = /tmp/mysql.sock
     pid_file                       = /var/run/mysqld/mysqld.pid
     # MyISAM #
     key_buffer_size                = 32M
     myisam_recover                 = FORCE,BACKUP
     # SAFETY #
     max_allowed_packet             = 16M
     max_connect_errors             = 1000000
     skip_name_resolve
     sql_mode                       = STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION,NO_ZERO_DATE,NO_ZERO_IN_DATE,ONLY_FULL_GROUP_BY
     sysdate_is_now                 = 1
     innodb                         = FORCE
     innodb_strict_mode             = 1
     # DATA STORAGE #
     datadir                        = /usr/local/mysql/data
     # BINARY LOGGING #
     log-bin                        =/usr/local/mysql/log/bin.log
     expire_logs_days               = 30
     sync_binlog                    = 1
     # CACHES AND LIMITS #
     key_buffer                     = 64M
     max_allowed_packet             = 16M
     sort_buffer_size               = 16M
     read_buffer_size               = 4M
     read_rnd_buffer_size           = 16M
     thread_stack                   = 8M
     tmp_table_size                 = 8M
     max_heap_table_size            = 2M
     query_cache_type               = 1
     query_cache_size               = 32M
     query_cache_limit              = 2M
     max_connections                = 2048
     thread_cache_size              = 512
     open_files_limit               = 65535
     table_definition_cache         = 400
     table_open_cache               = 2048
     # INNODB #
     innodb_log_files_in_group      = 2
     innodb_log_file_size           = 16M
     innodb_flush_log_at_trx_commit = 1
     innodb_file_per_table          = 1
     # 128M这个值视服务器内存而定
     innodb_buffer_pool_size        = 128M
     # 移除多余缓存
     performance_schema = 0
     # LOGGING #
     log-error=/usr/local/mysql/log/error.log
     general_log=1
     general_log_file=/usr/local/mysql/log/mysql.log
     slow_query_log=1
     slow_query_log_file=/usr/local/mysql/log/slowquery.log
     log-output=FILE
     # 避免MySQL的外部锁定,减少出错几率增强稳定性 #
     skip-external-locking
     # 禁止sql读取本地文件 #
     local-infile=0
    
  2. 将mysql的库文件路径加入系统的库文件搜索路径中
    方法一:直接做软链接
    # ln -s /usr/local/mysql/lib/ /usr/lib/mysql
    方法二:利用ldconfig导入系统库(推荐)
    # echo "/usr/local/mysql/lib" >> /etc/ld.so.conf.d/mysql.conf
    # ldconfig

  3. 输出mysql的头文件到系统头文件
    # ln -s /usr/local/mysql/include/mysql /usr/include/mysql

  4. 进入安装路径,初始化配置脚本
    # cd /usr/local/mysql
    # scripts/mysql_install_db --user=mysql --datadir=/usr/local/mysql/data
    在启动mysql初始化的时候可能会报一个错误,缺少per模块:

    解决方法yum安装per模块即可:
    # yum install -y perl-Module-Install.noarch
    然后重新执行:scripts/mysql_install_db --user=mysql --datadir=/usr/local/mysql/data
    出现这样就算好了,这个里面有个警告不用管,是我之前写好的my.cnf:

  5. 复制mysql启动脚本到系统服务目录
    # cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld

  6. 系统启动项相关配置
    # chkconfig --add mysqld #添加开机启动服务
    # chkconfig --level 35 mysqld on #设置mysql启动

  7. 启动mysql
    # service mysqld start
    查看是否成功:
    如果启动成功会出现starting mysql ..success!

    如果没有使用netstat命令查看有没有mysql进程的端口:
    # netstat -anplt | grep mysql

    注:从启MYSQL也可使用以下命令开启此服务
    # /usr/local/mysql/bin/safe_mysqld
    如果不设置chkconfig启动项,也可在/etc/rc.local下添加如下命令,使mysql服务利用系统启动脚本运行.
    # echo "/usr/local/mysql/bin/safe_mysqld --user=mysql &" >> /etc/rc.local

  8. 设置初始账户,并登陆后台(这个根据情况设置):

       # /usr/local/mysql/bin/mysqladmin -u root password 123456   #设置密码
       # /usr/local/mysql/bin/mysql -u root -p123456     #连接数据库
    
       mysql> create database phpwind;      #创建数据库
       mysql> grant all privileges on *.* to root@'%' identified by '123456' with grant option;  #给root用户非本地链接所有权限,并改密码和赋予其给其他人下发权限.
       mysql> show variables; #查看mysql设置.
    
  9. 添加mysql命令集到系统全局变量
    >注:如果系统之前未安装mysql客户端,可以将编译好的mysql命令集导入系统全局变量
    >以后就可以直接使用mysql命令集,而不需要使用绝对路径访问.
    ># echo "PATH=$PATH:/usr/local/mysql/bin;export PATH" >> /etc/profile
    ># source /etc/profile

四.编译安装nginx(官方文档http://wiki.nginx.org/Main)

  1. 模块依赖性:
    gzip 模块需要 zlib 库
    rewrite 模块需要 pcre 库
    ssl 功能需要 openssl 库
    # yum install gcc openssl-devel pcre-devel zlib-devel

  2. nginx编译
    先添加nginx用户和用户组
    # groupadd nginx
    # useradd -g nginx -s /bin/false -M nginx
    # tar zxvf nginx-1.8.1.tar.gz
    # cd nginx-1.8.1
    # ./configure --prefix=/usr/local/nginx --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_dav_module --with-http_flv_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-mail --with-mail_ssl_module --with-debug --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fastcgi --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi
    # make && make install
    创建缓存目录:
    # mkdir -p /var/tmp/nginx/client

  3. 创建启动脚本

          # vi /etc/init.d/nginx
    
                 #!/bin/sh
                 #
                 # nginx - this script starts and stops the nginx daemin
                 #
                 # 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
                 # 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"
                 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
                    sleep 1
                    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
    
    
           # chmod 755 /etc/init.d/nginx
           # chkconfig --add nginx
           # service nginx start
           # chkconfig nginx on
         >备注:如果开启iptables:
           #iptables –I INPUT –p tcp –dport 80 –j ACCEPT
           #service  iptables save
           #service iptables restart
        启动成功如图:
        这个是加入了nginx配置文件的检测,所有看到上面两行
    
  4. 访问测试页面:
    浏览器输入:http://你的服务器的ip或者域名

五. 安装php模块

  1. 处理依赖包
    暂无
  2. 安装PHP
    # tar zxvf php-5.6.20.tar.gz
    # cd php-5.6.20
    此处编译安装了我们项目经常用到的PHP模块,如有其它需要可以自定义添加.
    #./configure --prefix=/usr/local/php5 --enable-fastcgi --enable-fpm --with-libxml-dir=/usr/local/lib --with-zlib-dir=/usr/local/lib --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-gd --enable-soap --enable-sockets --enable-xml --enable-mbstring --with-png-dir=/usr/local --with-jpeg-dir=/usr/local --with-curl=/usr/lib --with-freetype-dir=/usr/include/freetype2/freetype/ --enable-bcmath --enable-zip --enable-maintainer-zts

在“./configure”编译选项中,“--enable-fastcgi”是启用对PHP的FastCGI支持,“--enable-fpm”是激活对FastCGI模式的fpm支持。
在编译时候会出现这样的错误:
翻阅php安装包中的INSTALL文件发现有这样一句话:
Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is
automagically enabled in php-cgi in PHP 5.3, but for older versions
configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi
enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3,
fastcgi was enabled on the php binary (there was no php-cgi).
大概意思说:FastGCshi连接 php和Lighttpd的首选项,在php5.3中是自动启用的,只有在老版本里面需要添加--enable-fastcgi,如果想确认是否启用fastgci,在php5.2.3之前使用php –v查看,php5.2.5应该包含(cgi-fcgi),fastcgi在php程序中启用的。
一句话就是:php5.3之后的版本是不用加--enable-fastcgi

   # make
   # make install

在make && make install报错:

Libtool版本不不是有效的,执行:yum install libtool更新安装

   # yum install libtool

成功结果:

  1. 安装结束后:
    添加php配置文件,需要CP 一个源码里面的php.ini-development或php.ini-production 到/usr/local/php/lib 为 php.ini
    # cd php-5.6.20
    # cp php.ini-development /usr/local/php5/lib/php.ini

  2. PHP配置: (修改php.ini,默认目录/usr/local/php5/lib/php.ini)
    # vi /usr/local/php5/lib/php.ini

     expose_php = Off   #363行
     display_errors = Off  #446行
     date.timezone =PRC  #925行
     log_errors = On      #1200行添加
     error_log = /usr/local/nginx/logs/php_error.log
    
  3. 配置启动FastCGI进程:
    # cd /usr/local/php5/etc/
    # cp php-fpm.conf.default php-fpm.conf
    优化配置:
    # vi php-fpm.conf

内存小于4G服务器(值可逐级递减):
修改如下参数:

   pm=dynamic          #224行
   pm.max_children=40   #235行
   pm.start_servers=10    #240行
   pm.min_spare_servers=10  #245行
   pm.max_spare_servers=40  #250行

内存大于4G服务器(值可逐级递增):
修改如下参数:

  pm=static
  pm.max_children=100

修改php-fpm属主

  user = www #149行
  group = www  #159行

注:这里的user和group名建议与/usr/local/nginx/conf/nginx.conf内的属主与属组保持一致

 user www www;

最后在nginx/html目录下将具体虚拟目录的属主属组也改成www与www,保证PHP程序对该目录有读写权限.

注:LNMP与LAMP的PHP执行区别:
LAMP下PHP相当于APACHE下的一个模块,所有执行权限都由APACHE统一管理,用户访问WEB页面相当于调用系统创建的APACHE属主和属组的权限进行PHP页面操作,最后将PHP执行结果返回给用户.
LNMP下PHP相当于用户执行WEB浏览首先会去执行NIGNX反向代理,该代理会将访问请求转发给本地PHP服务进程php-fpm(端口号默认9000),然后利用该进程执行WEB下的PHP文件,最后将PHP执行结果返回给用户,因为其属主属组都为www,所以对属主属组为www的目录都有读写权限,当然前提你的目录u=r+w+x
当PHP有内建shell语句时,也会走相应命令或脚本的用户权限.这样就保证开发人员在执行PHP语句时能对项目下的文件具有读写权限,避免运维人员二次手动对需要读写的子目录设置777权限,提高项目的安全性.
通过打印phpinfo()内建函数也能看到两者的区别:

  1. 启动服务:

    # /usr/local/php5/sbin/php-fpm
    # ps -ef|grep php-fpm
    

重启fpm:
# pkill php-fpm
# /usr/local/php5/sbin/php-fpm
加入开机启动:
# echo "/usr/local/php5/sbin/php-fpm" >> /etc/rc.local

  1. 配置nginx支持php:

    由于Nginx本身不会对PHP进行解析,因此要实现Nginx对PHP的支持,其实是将对PHP页面的请求交给fastCGI进程监听的IP地址及端口。如果把php-fpm当做动态应用服务器,那么Nginx其实就是一个反向代理服务器。
    Nginx通过反向代理功能实现对PHP的解析,这就是Nginx实现PHP动态解析的原理。
    这里假定Nginx的安装目录为/usr/local,则Nginx配置文件的路径为/usr/local/nginx/conf/nginx.conf。下面是在Nginx下支持PHP解析的一个虚拟主机配置实例。

(版本一)
# vi /usr/local/nginx/conf/nginx.conf
添加到http层级:

     server {
     server_name "www.abc.com";
    location / {
    index index.html index.php;
    root /usr/local/nginx/html/www.abc.com;
    }
    location ~ \.php$ {
          root           html;
          fastcgi_pass   127.0.0.1:9000;
          fastcgi_index  index.php;
          fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html/www.abc.com$fastcgi_script_name;
          include        fastcgi_params;
    }
   }

通过location指令,将所有以php为后缀的文件都交给127.0.0.1:9000来处理,而这里的IP地址和端口就是FastCGI进程监听的IP地址和端口。
fastcgi_param指令指定放置PHP动态程序的主目录,也就是$fastcgi_script_name前面指定的路径,这里是/usr/local/nginx/html/www.abc.com目录,建议将这个目录与Nginx虚拟主机指定的根目录保持一致.
fastcgi_params文件是FastCGI进程的一个参数配置文件,在安装Nginx后,会默认生成一个这样的文件,这里通过include指令将FastCGI参数配置文件包含了进来。

(版本二)推荐

    # vi /usr/local/nginx/conf/nginx.conf

添加到http层级:

添加vhost配置文件

   include "/usr/local/nginx/conf/vhost/*.conf";
   
   # mkdir /usr/local/nginx/conf/vhost
   # vi /usr/local/nginx/conf/vhost/default.conf
   
   server {
        listen 80;
        server_name "www.abc.com";
        index index.html index.php;
        root /usr/local/nginx/html/www.abc.com;
        location ~ .*\.(php|php5)?$ {
             fastcgi_pass    127.0.0.1:9000;
             fastcgi_index   index.php;
             include         fastcgi.conf;
       }
   }

注:
~ .*为不区分大小写匹配
.转义为.
(php|php5)?$ 结尾匹配一个或零个php或者php5

  1. 测试NGINX是否加载PHP

    # vi  /usr/local/nginx/html/www.abc.com/info.php
    
     
    

    重启nginx服务
    # service nginx restart
    检查80端口是否打开
    # lsof -i:80

  2. 浏览器输入(注意修改本机HOST文件)

    http://www.abc.com/info.php
    显示有如下测试页面内容,PHP在GNINX下加载成功

你可能感兴趣的:(LNMP环境搭建)