個人嘗試在Debian Jessie 8.6中構建LEMP開發環境,其中Web服務器爲Nginx,DBMS爲Percona,開發語言爲PHP,此前已在個人筆電上配置成功。本文主要記錄安裝、配置LEMP開發環境的完整過程,所有操作在Digital Ocean的VPS中進行。

因是在VPS上操作,故直接使用root用戶進行操作,如果是普通用戶(如lemp),可在文件/etc/sudoers中添加

# User privilege specification
root    ALL=(ALL:ALL) ALL
#需要添加的行
lemp  ALL=NOPASSWD:ALL

實現免密碼執行sudo權限。

爲方便使用 普通用戶帳號 登錄的用戶,本文中執行的命令皆添加sudo

: 本文不涉及防火牆規則的設置,請知悉。

Operation System Preparation

操作環境準備

Digital Ocean中創建Droplets,操作系統選擇Debian 8.6 x64,通過SSH遠程登陸進行操作(通過key登陸),登錄命令

ssh -C -c aes256-ctr root@138.197.2.248

系統信息

#內核版本
root@lempstacker:~# uname -r
3.16.0-4-amd64

#發行版信息
root@lempstacker:~# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=debian
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
root@lempstacker:~#

需要進行的操作有 * 更換resource源 * 更新系統 * 更改時區爲Asia/Shanghai(根據所在地區具體設置),設置NTP * 安裝Vim文本編輯器

Changing Apt Source

Debian Jessie中source所在目錄爲

# 文件
/etc/apt/sources.list

# 目錄
/etc/apt/sources.list.d/

本文中Nginx、Percona的官方repo將安裝在目錄/etc/apt/sources.list.d/中。

Digital Ocean默認使用的是其自家提供的鏡像,對於中國大陸地區的用戶,可選擇使用163提供的Debian鏡像,頁面中有具體的操作說明。

此處仍使用Digital Ocean默認的source,不更改source源。

Updating System

設置apt source後,更新操作系統

執行如下命令進行系統更新

#更新軟件包列表
sudo apt-get update

#系統級更新
sudo apt-get upgrade -y

#發行版本級更新
sudo apt-get dist-upgrade -y
# --force-yes

GNome Desktop Setting

如果使用GNome 3桌面環境,默認會記錄當前用戶打開的文件,在 Recent 窗口中列出。通過如下設置禁用該功能

[[ -f ~/.local/share/recently-used.xbel ]] && rm -f ~/.local/share/recently-used.xbel

[[ -f ~/.config/gtk-3.0/settings.ini ]] && sed -i -r '/^gtk-recent-files/d;/^\[Settings\]/a gtk-recent-files-max-age=0\ngtk-recent-files-limit=0' ~/.config/gtk-3.0/settings.ini

設置方法參考自Blog DISABLING GNOME’S RECENTLY-USED FILE LIST, THE BETTER WAY

Setting TimeZone & Syncing Network Time

設置時區(Asia/Shanghai),與網絡時間同步

時區信息可通過如下命令獲取

date +'%Z %z'

timedatectl

使用如下命令更改時區

#更改時區爲 Asia/Shanghai
sudo timedatectl set-timezone Asia/Shanghai

#安裝chrony進行時間同步
sudo apt-get install chrony -y

#啓動chrony服務並設置爲開機自動啓動
sudo systemctl start chrony
sudo systemctl enable chrony

#啓用NTP
sudo timedatectl set-ntp true

操作完成後,可通過timedatectl查看時區、時間等信息。

root@lempstacker:~# date
Thu Dec  8 22:13:03 CST 2016
root@lempstacker:~# timedatectl
      Local time: Thu 2016-12-08 22:13:07 CST
  Universal time: Thu 2016-12-08 14:13:07 UTC
        RTC time: Thu 2016-12-08 14:13:06
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: yes
NTP synchronized: yes
 RTC in local TZ: no
      DST active: n/a
root@lempstacker:~#

Installing Vim Editor

如果系統未安裝vim編輯器,建議安裝

#安裝vim編輯器
sudo apt-get install vim -y

需注意,在Debian中vim的配置文件路徑是/etc/vim/vimrc,而在CentOS中其路徑爲/etc/vimrc

具體參數配置參見本人Blog VIM Editor Configuration


LEMP Info Introduce

LEMP中各軟件的具體信息

Software Version
Nginx 1.10.2
Percona 5.7.16-10
PHP 5.6.27

Nginx的source配置參考自 * nginx: Linux packages * Install

Percona的source配置參考自 * Installing Percona Server on Debian and Ubuntu * Update the Signing Key for Percona Debian and Ubuntu Packages

PHP的source無須額外配置,安裝參考自 * Debian GNU/Linux installation notes * PHP and Debian

Installing LEMP

安裝LEMP開發套件

Nginx Installation

根據上文列出的參考文檔,執行如下命令

#添加Nginx官方Source,採用https
sudo tee /etc/apt/sources.list.d/nginx.list <<-'EOF'
deb https://nginx.org/packages/debian/ jessie nginx
deb-src https://nginx.org/packages/debian/ jessie nginx
EOF

#下載並安裝Nginx的PGP key
cd /tmp
curl -sO http://nginx.org/keys/nginx_signing.key
sudo apt-key add nginx_signing.key
rm -f /tmp/nginx_signing.key

#更新軟件包列表
sudo apt-get update

#安裝Nginx Web服務器
sudo apt-get install nginx -y

#啓動Nginx服務並設置爲開機自動啓動
sudo systemctl start nginx
sudo systemctl enable nginx

操作完成後查看

#查看版本號
root@lempstacker:~# nginx -v
nginx version: nginx/1.10.2

#查看版本號,編譯器版本,腳本配置參數
root@lempstacker:~# nginx -V
nginx version: nginx/1.10.2
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1t  3 May 2016
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-file-aio --with-threads --with-ipv6 --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_ssl_module --with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed'
root@lempstacker:~#

#抓取頁面HTTP Header信息
#使用迴環地址
root@lempstacker:~# curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Thu, 08 Dec 2016 15:02:01 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 18 Oct 2016 15:03:13 GMT
Connection: keep-alive
ETag: "580639b1-264"
Accept-Ranges: bytes

#使用外網地址
root@lempstacker:~# curl -I 138.197.2.248
HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Thu, 08 Dec 2016 15:02:03 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 18 Oct 2016 15:03:13 GMT
Connection: keep-alive
ETag: "580639b1-264"
Accept-Ranges: bytes

root@lempstacker:~#

Percona Installation

根據上文列出的參考文檔,執行如下命令

方式1: 通過deb包添加

#下載deb安裝包
cd /tmp
curl -sO https://repo.percona.com/apt/percona-release_0.1-4.$(lsb_release -sc)_all.deb

#安裝
sudo dpkg -i percona-release_0.1-4.$(lsb_release -sc)_all.deb
rm -f percona-release_0.1-4.$(lsb_release -sc)_all.deb

方式2: 手動添加

#添加Nginx官方Source
sudo tee /etc/apt/sources.list.d/percona-release.list <<-'EOF'
# Percona releases, stable
deb http://repo.percona.com/apt jessie main
deb-src http://repo.percona.com/apt jessie main
EOF

#安裝Percona的GPG Key
sudo apt-key adv --keyserver keys.gnupg.net --recv-keys 8507EFA5

兩種方式的操作結果一致,繼續如下操作

#更新軟件包列表
sudo apt-get update

#安裝Percona 5.7
sudo apt-get install percona-server-server-5.7 -y

#啓動MySQL服務並設置爲開機自動啓動
sudo systemctl start mysql
sudo systemctl enable mysql

重要:安裝過程中會出現提示框,要求爲root用戶輸入密碼

Please provide a strong password that will be set for the root account of your MySQL database. Leave it blank to enable password less login using UNIX socket based authentication.

根據自身意願選擇是否設置,如果設置,會要求再次輸入相同密碼以確認兩次密碼輸入一致。此處暫不設置,密碼爲空。

安裝完成後出現如下信息

* Percona Server is distributed with several useful UDF (User Defined Function) from Percona Toolkit.
* Run the following commands to create these functions:

    mysql -e "CREATE FUNCTION fnv1a_64 RETURNS INTEGER SONAME 'libfnv1a_udf.so'"
	mysql -e "CREATE FUNCTION fnv_64 RETURNS INTEGER SONAME 'libfnv_udf.so'"
	mysql -e "CREATE FUNCTION murmur_hash RETURNS INTEGER SONAME 'libmurmur_udf.so'"

* See http://www.percona.com/doc/percona-server/5.7/management/udf_percona_toolkit.html for more details

根據自身意願選擇是否執行。

操作完成後查看

root@lempstacker:~# mysql -V
mysql  Ver 14.14 Distrib 5.7.16-10, for debian-linux-gnu (x86_64) using  6.3
root@lempstacker:~#

PHP Installation

可通過如下命令查看source源中有哪些PHP相關的軟件包

apt-cache search -n php

#提取與PHP相關的軟件包名
apt-cache search -n php5 | awk '{print $1}'

#安裝PHP相關包
sudo apt-get install -y \
php5 \
php5-cgi \
php5-cli \
php5-fpm \
php5-common \
php5-curl \
php5-dbg \
php5-dev \
php5-enchant \
php5-gd \
php5-gmp \
php5-imap \
php5-interbase \
php5-intl \
php5-ldap \
php5-mcrypt \
php5-mysqlnd \
php5-odbc \
php5-phpdbg \
php5-pspell \
php5-readline \
php5-recode \
php5-snmp \
php5-tidy \
php5-xmlrpc \
php5-xsl \
php5-librdf \
php5-remctl \
php5-twig \
php5-uprofiler \
php5-xcache \
php5-xdebug \
php5-xhprof \
php5-exactimage \
php5-gdcm \
php5-vtkgdcm \
php5-geos \
php5-lasso \
php5-libvirt-php \
php5-mapscript \
php5-adodb \
php5-gearman \
php5-geoip \
php5-gnupg \
php5-igbinary \
php5-imagick \
php5-json \
php5-memcache \
php5-memcached \
php5-msgpack \
php5-mysqlnd-ms \
php5-oauth \
php5-pecl-http \
php5-pecl-http-dev \
php5-pinba \
php5-propro \
php5-propro-dev \
php5-radius \
php5-raphf \
php5-raphf-dev \
php5-redis \
php5-rrd \
php5-sasl \
php5-solr \
php5-ssh2 \
php5-stomp \
php5-zmq

Version & Conf Path

安装完成后可通过如下命令查看具体版本及配置文件路径

Version Check

#nginx
sudo nginx -v 2>&1 | awk -v FS='/' '{print $NF}'
sudo nginx -v 2>&1 | sed -r -n 's@.*/(.*)@\1@p'

sudo nginx -V 2>&1 | awk -v FS='/' '{print $NF;exit}'
sudo nginx -V 2>&1 | sed -r -n '1 s@.*/(.*)@\1@p'

# - Bash 4+
sudo nginx -v |& awk -v FS='/' '{print $NF}'
sudo nginx -v |& sed -r -n 's@.*/(.*)@\1@p'

sudo nginx -V |& awk -v FS='/' '{print $NF;exit}'
sudo nginx -V |& sed -r -n '1 s@.*/(.*)@\1@p'

#mysql
mysql -V | sed -r -n 's@.*Distrib (.*),.*@\1@p'

#php
php -v | awk '{print $2;exit}'

Conf Path Check

#nginx
sudo nginx -V 2>&1 | sed -r -n 's@.*conf-path=(.*) --error.*@\1@p'

#mysql
mysql --help | awk '$0~/Default options/{getline;print}'
mysqladmin --help | awk '$0~/Default options/{getline;print}'

#php
php -i | awk '$0~/^Loaded Configuration File/{print $NF}'

Configuration

各軟件默認配置文件路徑

Software Conf Path
Nginx /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf
Percona /etc/mysql//etc/mysql/percona-server.conf.d/mysqld.cnf
PHP /etc/php5//etc/php5/fpm/php.ini
PHP-FPM /etc/php5/fpm/pool.d/www.conf

LEMP環境的配置具體可參考本人Blog * LEMP Installation and Nginx Optimization * Compiling And Installing Zabbix3.2 Based On LEMP On CentOS6.8 * Nginx Simple Usage on CentOS 7

建議:更改文件之前先進行備份!

以文件/etc/nginx/nginx.conf爲例

#在同一目錄下備份源文件
sudo cp -pv /etc/nginx/nginx.conf{,.old}

Nginx Configuration

Nginx的配置、優化涉及到內核參數的調整,具體參見LEMP Installation and Nginx Optimization中相關部分。

參照中LEMP Installation and Nginx Optimization的相關部分進行參數配置。

/etc/nginx/nginx.conf

參照 /etc/nginx/nginx.conf

# /etc/nginx/nginx.conf
user  nginx;
worker_processes  1;
worker_rlimit_nofile 65536;

pid        /var/run/nginx.pid;

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


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

	charset utf-8;
	server_tokens off;
	autoindex off;

	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

	sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # [debug|info|notice|warn|error|crit|alert|emerg]
    error_log  /var/log/nginx/error.log warn;
    access_log /var/log/nginx/access.log combined if=$loggable;

    #Conditional Logging
    map $status $loggable {
        ~^[23]  0;
        default 1;
    }

	#Keep Alive
    keepalive_timeout 50;
    keepalive_requests 100000;

    #Buffer Size
    client_body_buffer_size      128k;
    client_max_body_size         10m;
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
    output_buffers               1 32k;
    postpone_output              1460;

    #Timeouts
    client_header_timeout  3m;
    client_body_timeout    3m;
    send_timeout 90s;

    #Close connection on Missing Client Response
    reset_timedout_connection on;

    #Static Asset Serving
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 5;
    open_file_cache_errors off;

    # gzip compression
    gzip on;
    gzip_vary on;
    gzip_comp_level 5;
    gzip_buffers     16 8k;
    gzip_min_length 1000;
    gzip_proxied    expired no-cache no-store private auth;
    gzip_types      text/css application/javascript application/x-javascript text/javascript text/plain text/xml application/json application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype application/x-font-ttf application/xml font/eot font/opentype font/otf image/svg+xml image/vnd.microsoft.icon;
    gzip_disable    "MSIE [1-6]\.";

    gzip_static on;

    include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf.d/default.conf

參照 /etc/nginx/conf.d/default.conf

重點部分是對PHP的解析

#/etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        # 添加index.php
        index  index.php index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # 設置PHP解析
	location ~ \.php$ {
    	try_files $uri = 404;
    	root   /usr/share/nginx/html;
        #根據自身情況設置
    	fastcgi_pass unix:/var/run/php/php5-fpm.sock;
    	fastcgi_index index.php;
    	#fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    	include fastcgi_params;
	}
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

注意: 其中的unix:/var/run/php/php5-fpm.sock會在接下來的php-fpm參數配置中設置,請務必確保兩處的sock路徑一致。

Nginx配置文件修改完成後,使用如下命令 1. 查看是否配置文件有語法錯誤

sudo nginx -t
  1. 動態重新載入配置文件 bash sudo nginx -s reload

Nginx默認的Web Root路徑是/usr/share/nginx/html,其默認的user、group都是root用戶,此處將其更改爲nginx

sudo chown -R nginx:nginx /usr/share/nginx/html

Percona Configuration

參照 MariaDB Configuration

#/etc/mysql/percona-server.conf.d/mysqld.cnf
#
# The Percona Server 5.7 configuration file.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket   = /var/run/mysqld/mysqld.sock
port   = 3306
basedir    = /usr
datadir    = /var/lib/mysql
tmpdir   = /tmp
lc-messages-dir  = /usr/share/mysql
explicit_defaults_for_timestamp

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1

log-error    = /var/log/mysql/error.log

# Recommended in standard MySQL setup
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_ALL_TABLES

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

character_set_server = utf8
collation-server = utf8_general_ci
default-time_zone = '+8:00'

skip_name_resolve = 1
interactive_timeout = 600    # time seconds
wait_timeout = 600    # time seconds

# InnoDB Variables Setting
default_storage_engine = InnoDB

innodb_file_per_table = 1
innodb_strict_mode = 1
innodb_file_format_check = 1
innodb_buffer_pool_size = 256M    # Go up to 80% of your available RAM
#innodb_buffer_pool_instances = 8        # combine with innodb_buffer_pool_size,if its size < 1GB, the default value is 1
innodb_flush_method = O_DIRECT

# innodb_read_io_threads = 16    # If you have a strong I/O system or SSD
# innodb_write_io_threads = 32    # If you have a strong I/O system or SSD
# innodb_io_capacity = 10000    # If you have a strong I/O system or SSD
# innodb_io_capacity_max = 30000    # If you have a strong I/O system or SSD

innodb_flush_log_at_trx_commit = 2    # 1 for durability, 0 or 2 for performance
innodb_log_buffer_size = 16M
innodb_log_file_size = 64M # Bigger means more write throughput but longer recovery time


max_connections = 400    # Values < 1000 are typically good
max_user_connections = 300    # Limit one specific user/application
thread_cache_size = 400    # Up to max_connections makes sense
tmp_table_size = 16M

# Query
query_cache_type = 1
query_cache_size = 8M
max_allowed_packet = 32M

# Memory Table
#max_heap_table_size = 32M

log_timestamps = SYSTEM

# Slow Query Log
slow_query_log = 1
long_query_time = 1.5
slow_query_log_file = /var/log/mysql/percona_slow.log
#log_queries_not_using_indexes=1
#min_examined_row_limit = 100


# Record General Query Log
general_log_file = /var/log/mysql/percona_general.log
general_log = 1

# Error Log
log_error = /var/log/mysql/percona_error.log
log_warnings = 2
# log_error_verbosity = 3
innodb_print_all_deadlocks = 1


# Binary Logging
server_id = 1
log_bin = percona-bin
log_bin_index = percona-bin.index       #The index file for binary log file names.
binlog_format=mixed
binlog_cache_size = 1M
binlog_stmt_cache_size = 1M
max_binlog_size = 32M
sync_binlog = 1
expire_logs_days = 15
binlog_row_image = full

注意: 其中的部分參數需根據服務器的實際硬件配置情況設置。

執行如下操作重啓Percona服務

sudo systemctl restart mysql

如果未啓動成功,可通過查看錯誤日誌/var/log/mysql/error.log判斷故障原因。

執行如下命令進行安全設置

mysql_secure_installation

具體過程如下

創建普通用戶,在登入Percona後執行如下操作

create user 'lemp'@'localhost' identified by 'lemp@Asia_Sun2016';
grant all on *.* to 'lemp'@'localhost';
flush privileges;

在用戶家目錄下創建文件~/.my.cnf

tee ~/.my.cnf <<-'EOF'
[client]
user=lemp
password=lemp@Asia_Sun2016
EOF

chmod 400 ~/.my.cnf

可實現免密碼登錄 ,直接執行mysql即可。

PHP-FPM Configuration

參照 PHP Configuration

/etc/php5/fpm/php.ini

#關閉Nginx文件類型錯誤解析
;cgi.fix_pathinfo=1
cgi.fix_pathinfo=0

#設置時區
;date.timezone =
date.timezone = Asia/Shanghai

#禁止顯示PHP版本信息
;expose_php = On
expose_php = Off

#支持PHP短標籤
;short_open_tag = On
short_open_tag = Off

/etc/php5/fpm/pool.d/www.conf

# 23-24行
;user = www-data
;group = www-data
user = nginx
group = nginx

# 38行,此處須與Nginx中一致
;listen = /var/run/php5-fpm.sock
listen = /var/run/php/php5-fpm.sock

#如果不指定爲nginx,無法正常監聽php-fpm.sock
# 49~51行
;listen.owner = www-data
;listen.group = www-data
;listen.mode = 0660
listen.owner = nginx
listen.group = nginx
listen.mode = 0660

默認php5-fpm.pidphp5-fpm.sock都在/var/run目錄下

root@lempstacker:~# ls -lh /var/run/php5-fpm.*
-rw-r--r-- 1 root     root     4 Dec  8 23:30 /var/run/php5-fpm.pid
srw-rw---- 1 www-data www-data 0 Dec  8 23:30 /var/run/php5-fpm.sock
root@lempstacker:~#

路徑/var/run/php/默認不存在,需手動創建,並將owner, group從默認的www-data更改爲nginx,執行如下命令

[[ ! -d /var/run/php ]] && sudo mkdir -pv /var/run/php
sudo chown -R nginx:nginx /var/run/php

注意: 文件/var/run/php5-fpm.pid/lib/systemd/system/php5-fpm.service使用,故需要修改文件php5-fpm.service中的參數PIDFile

#/lib/systemd/system/php5-fpm.service
[Unit]
Description=The PHP FastCGI Process Manager
After=network.target

[Service]
Type=notify
PIDFile=/var/run/php/php5-fpm.pid
ExecStartPre=/usr/lib/php5/php5-fpm-checkconf
ExecStart=/usr/sbin/php5-fpm --nodaemonize --fpm-config /etc/php5/fpm/php-fpm.conf
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
#添加服務別名
Alias=php-fpm.service

注意: 如果目錄/var/lib/php/session存在,建議執行如下操作

chown -R nginx:nginx /var/lib/php/session

重啓php-fpm服務

sudo systemctl daemon-reload
sudo systemctl restart php5-fpm
#or
sudo systemctl restart php-fpm

Warning: Unit file of php5-fpm.service changed on disk, ‘systemctl daemon-reload’ recommended.

重要: 請勿忘記重啓Nginx服務

sudo systemctl restart nginx

否則PHP文件無法被Nginx解析,會出現文件下載提示信息。

Testing

測試

PHP Probe Testing

PHP探針

Nginx默認的Web Root路徑是/usr/share/nginx/html

sudo tee /usr/share/nginx/html/index.php <<-'EOF'
<?php
    phpinfo();
?>
EOF

Database Connection Testing

Method 1 mysql_connect

根據mysql_connect進行數據庫連接測試

sudo tee /usr/share/nginx/html/index.php <<-'EOF'
<?php
$link = mysql_connect('localhost', 'lemp', 'lemp@Asia_Sun2016');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo "Connected successfully"."<br>";
echo date('Y-m-d H:i:s');
mysql_close($link);
?>
EOF

Method 2 PDO

sudo tee /usr/share/nginx/html/index.php <<-'EOF'
<?php
$db = new PDO('mysql:host=localhost;port=3306','lemp','lemp@Asia_Sun2016');

$sql = "select user,host from mysql.user";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>';
print_r($rows);
echo date('Y-m-d H:i:s');
EOF


Change Logs

  • 2016.12.09 02:16 Fri Asia/Shanghai
    • 初稿完成
  • 2016.12.27 17:47 Tue Asia/Shanghai
    • 添加检测LEMP软件的版本及配置文件路径命令
  • 2017.02.02 17:18 Thu America/Boston
    • 添加GNome Desktop Setting,禁止記錄最近打開文件