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
    
     <?php
     echo phpinfo();
     ?>
    

    重啟nginx服務
    # service nginx restart
    檢查80端口是否打開
    # lsof -i:80

  2. 瀏覽器輸入(注意修改本機HOST文件)

    http://www.abc.com/info.php
    顯示有如下測試頁面內容,PHP在GNINX下加載成功

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容