shell 格式化输出nginx的编译参数

命令

nginx -V > nginx.txt
cat -n nginx.txt  | sed -n '5,18p' | awk '{$1="";print $0}' 
| sed 's/^[ ]*//g'  | tr 'n' ',' | sed -n 's/,//gp' | tr " " "n"

结果

configure
arguments:
--user=nginx
--group=nginx
--prefix=/usr/share/nginx
--sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--http-client-body-temp-path=/var/lib/nginx/tmp/client_body
--http-proxy-temp-path=/var/lib/nginx/tmp/proxy
--http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi
--http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi
--http-scgi-temp-path=/var/lib/nginx/tmp/scgi
--pid-path=/var/run/nginx.pid
--lock-path=/var/lock/subsys/nginx
--with-http_ssl_module
--with-http_spdy_module
--with-http_v2_module
--with-http_realip_module
--with-http_addition_module
--with-http_xslt_module
--with-http_image_filter_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_gzip_static_module
--with-http_secure_link_module
--with-http_degradation_module
--with-http_stub_status_module
--with-debug
--with-http_sysguard_module
--with-http_upstream_check_module
--with-http_lua_module
--with-http_dyups_module
--with-luajit-lib=/usr/lib
--with-luajit-inc=/usr/include/luajit-2.0

解释:

awk '{$1="";print $0}'

输出第2列至最后一列(即排除第一列)

 sed 's/^[ ]*//g'

去掉行首的空格

tr 'n' ',' | sed -n 's/,//gp'

去掉换行符,先把换行符替换成逗号(或者#¥%&等),然后再讲逗号删除。

ngxtop:在命令行实时监控 Nginx 的神器

Nginx网站服务器在生产环境中运行的时候需要进行实时监控。实际上,诸如Nagios, Zabbix, Munin 的网络监控软件是支持 Nginx 监控的。

如果你不需要以上软件提供的综合性报告或者长期数据统计功能,只是需要一种快速简便的办法去监控 Nginx 服务器的请求的话,我建议你采用一个叫 ngxtop 的命令行工具。

你马上就会发现 ngxtop 从界面和名称都借鉴了著名的top命令。ngxtop 是通过分析 Nginx 或者其他的日志文件,使用类似 top 命令的界面实时展示出来的。你可以说你知道的其他高端监控工具,但是在简洁这方面 ngxtop 无疑是最好的。简单就意味着不可替代。

本指南中,我将介绍如何使用 ngxtop 实时监控 Nginx 网站服务器。

Linux 上安装 ngxtop

首先在 Linux 系统中安装依赖库pip(LCTT译注:ngxtop是用python编写的)。

然后使用如下命令安装 ngxtop。

$ sudo pip install ngxtop

ngxtop 使用

基本使用方法如下:

ngxtop [options]
ngxtop [options] (print|top|avg|sum) <var>
ngxtop info

这里是一些通用选项。

  • -l : 指定日志文件的完整路径 (Nginx 或 Apache2)
  • -f : 日志格式
  • –no-follow: 处理当前已经写入的日志文件,而不是实时处理新添加到日志文件的日志
  • -t : 更新频率
  • -n : 显示行号
  • -o : 排序规则(默认是访问计数)
  • -a …, –a …: 添加表达式(一般是聚合表达式如: sum, avg, min, max 等)到输出中。
  • -v: 输出详细信息
  • -i : 只处理符合规则的记录

以下是一些内置变量,他们的含义不言自明。

  • bodybytessend
  • http_referer
  • httpuseragent
  • remote_addr
  • remote_user
  • request
  • status
  • time_local

使用 ngxtop 监控 Nginx

ngxtop 默认会从其配置文件 (/etc/nginx/nginx.conf) 中查找 Nginx 日志的地址。所以,监控 Nginx ,运行以下命令即可:

$ ngxtop

这将会列出10个 Nginx 服务,按请求数量排序。

显示前20个最频繁的请求:

$ ngxtop -n 20

未分类

获取Nginx基本信息:

$ ngxtop info

未分类

你可以自定义显示的变量,简单列出需要显示的变量。使用 “print” 命令显示自定义请求。

$ ngxtop print request http_user_agent remote_addr

未分类

显示请求最多的客户端IP地址

$ ngxtop top remote_addr

未分类

显示状态码是404的请求

$ ngxtop -i 'status == 404' print request status

未分类

除了Nginx,ngtop 还可以处理其他的日志文件,比如 Apache 的访问文件。使用以下命令监控 Apache 服务器:

$ tail -f /var/log/apache2/access.log | ngxtop -f commo

Nginx下使用Fastcgi_cache和ngx_pagespeed优化WordPress性能

今天要给大家分享的是最近明月一直在折腾的一个基于 Nginx 的静态化缓存方法,这个方法不是依托于 WordPress 系统的,而是直接在 WEB 服务器层面生成和调取静态化缓存的,可以说在执行效能上是 WordPress 插件静态化的效能无法比拟的,再配合ngx_pagespeed模块使用 Google 的 PageSpeed 技术压缩优化 js、css、图片等静态文件后,直接让 WordPress 在服务器层面就达到最佳的性能表现。
Nginx下使用Fastcgi_cache和ngx_pagespeed优化WordPress性能

未分类

最近也不知道是咋回事儿了,一直用的好好的 WP-Rocket 2.9.9版突然有一天造成 WordPress 登录失效了,无论如何都无法正常的登录后台,只有停用 WP-Rocket 后才可以正常登录,安装最新版 WP-Rocket 又出现频繁的报错和授权验证失败的问题,没办法只能舍弃这个缓存神器了。这时候想起里以前在【张戈博客】看到一篇【Nginx开启fastcgi_cache缓存加速,支持html伪静态页面】的文章,正好目前已经用的是 Nginx 了,所以就照着此文开始折腾了起来,没有想到竟然一步成功了,嘿嘿!

测试后发现缓存效果相当的“棒”,直接 WEB 服务器层面的缓存静态化表现真的是相当的“彪悍”呀,速度提升实在是太明显了。具体的教程我就不在这里过多的赘述了,大家可以参考【张戈博客】上文章即可了,里面说的是非常的明确了,如果是多站点的话可参考【Nginx配置多站点下的Proxy_cache或Fastcgi_cache缓存加速】,多思考、多实践一定可以成功的。运用 Nginx 配置文件的灵活性可以达到非常好的效果的。

顺便分享一点儿小知识,那就是 Nginx 下fastcgi_cache和proxy_cache的区别:

Nginx的Fastcgi_cache模块与Proxy_cache模块缓存区别

  1. proxy_cache的作用是缓存后端服务器的内容,包括静态的和动态。
  2. fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。
  3. proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。
  4. fastcgi_cache缓存减少了nginx与php的通信的次数,更减轻了php和数据库(mysql)的压力,这比用memcached之类的缓存要轻松得多。

静态化缓存实现了,发现服务器的负载一直都保持很低,于是又开始考虑在 Nginx 里加入ngx_pagespeed模块来“锦上添花”(特别强调:ngx_pagespeed模块适合独立主机使用,虚拟主机的话不建议使用,因为ngx_pagespeed模块会增加主机CPU的负载的,鱼与熊掌不可兼得呀!),虽然几天以来在 Nginx 添加模块编译的时候尝试了多次失败后终于还是成功了(请参考【Nginx 模块 ngx_pagespeed-1.12.34.2-stable 终于编译成功了】),并且用上 ngx_pagespeed-1.12.34.2-stable 最新版,这个版本支持 Redis 的,好像是可以把一些静态文件比如: js、css、图片等的优化压缩工作放到 Redis 里(可以理解为内存里)来提升优化效能。

未分类

在使用ngx_pagespeed模块后明月以外的发现博客调用的 Google AdSense 广告代码载入时间也提升了不少,甚至很多的外链js、css调用载入速度都有所提升。 CDN 流量好像也节约了一点点,哈哈,真的好意外的效果呀。

还有一个意外惊喜,文章列表页的缩略图片竟然被ngx_pagespeed给转换成 WebP 格式了,哈哈!牛逼呀!

下面分享一下明月目前使用的ngx_pagespeed模块的配置,从这些配置上大家就可以感受到ngx_pagespeed的强大了:

# 启用ngx_pagespeed
pagespeed on;
#指定ngx_pagespeed缓存路径
pagespeed FileCachePath /var/ngx_pagespeed_blog_cache;
# 禁用CoreFilters
pagespeed RewriteLevel PassThrough;
#开启使用Redis
pagespeed RedisServer "host:port";
# X-Header 值,用于判断是否生效
pagespeed XHeaderValue "Powered By www.mydomain.com";
# 过滤规则
#pagespeed RewriteLevel OptimizeForBandwidth;
# 不需过滤的目录或文件
pagespeed Disallow "*/wp-admin/*";
pagespeed Disallow "*/wp-login.php*";
# 启用压缩空白过滤器
pagespeed EnableFilters collapse_whitespace;
 # 启用JavaScript库卸载
 pagespeed EnableFilters canonicalize_javascript_libraries;
# 把多个CSS文件合并成一个CSS文件(比较容易引起主题版面混乱,所以我禁用了
#pagespeed EnableFilters combine_css;
# 把多个JavaScript文件合并成一个JavaScript文件,禁用原因同上,大家可以酌情开启
#pagespeed EnableFilters combine_javascript;
# 删除带默认属性的标签
 pagespeed EnableFilters elide_attributes;
# 改善资源的可缓存性
 pagespeed EnableFilters extend_cache;
# 更换被导入文件的@import,精简CSS文件
 pagespeed EnableFilters flatten_css_imports;
 pagespeed CssFlattenMaxBytes 5120;
# 延时加载客户端看不见的图片
 pagespeed EnableFilters lazyload_images;
# 启用JavaScript缩小机制
 pagespeed EnableFilters rewrite_javascript;
# 启用图片优化机制
 pagespeed EnableFilters rewrite_images;
# 预解析DNS查询
 pagespeed EnableFilters insert_dns_prefetch;
# 重写CSS,首先加载渲染页面的CSS规则
 pagespeed EnableFilters prioritize_critical_css;

如果你用的也是 Nginx 的话记得一定不要忘了Fastcgi_cache和ngx_pagespeed这两个模块哦,这绝对是两个优化 WordPress 的神器呀,这里明月的叹服一下 Nginx 了,真心好牛逼呀,据说还有非常多的神乎其技的功能呢,明月正在努力的折腾学习中,以后要好的收获了我一定会及时分享给大家的。

nginx log常用统计

IP相关统计

统计IP访问量

awk '{print $1}' access.log | sort -n | uniq | wc -l

查看某一时间段的IP访问量(4-5点)

grep "07/Apr/2017:0[4-5]" access.log | awk '{print $1}' | sort | uniq -c| sort -nr | wc -l

查看访问最频繁的前100个IP

awk '{print $1}' access.log | sort -n |uniq -c | sort -rn | head -n 100

查看访问100次以上的IP

awk '{print $1}' access.log | sort -n |uniq -c |awk '{if($1 >100) print $0}'|sort -rn

查询某个IP的详细访问情况,按访问频率排序

grep '104.217.108.66' access.log |awk '{print $7}'|sort |uniq -c |sort -rn |head -n 100

页面访问统计

查看访问最频的页面(TOP100)

awk '{print $7}' access.log | sort |uniq -c | sort -rn | head -n 100

查看访问最频的页面([排除php页面】(TOP100)

grep -v ".php" access.log | awk '{print $7}' | sort |uniq -c | sort -rn | head -n 100

查看页面访问次数超过100次的页面

cat access.log | cut -d ' ' -f 7 | sort |uniq -c | awk '{if ($1 > 100) print $0}' | less

查看最近1000条记录,访问量最高的页面

tail -1000 access.log |awk '{print $7}'|sort|uniq -c|sort -nr|less

每秒请求量统计

统计每秒的请求数,top100的时间点(精确到秒)

awk '{print $4}' access.log |cut -c 14-21|sort|uniq -c|sort -nr|head -n 100

每分钟请求量统计

统计每分钟的请求数,top100的时间点(精确到分钟)

awk '{print $4}' access.log |cut -c 14-18|sort|uniq -c|sort -nr|head -n 100

每小时请求量统计

统计每小时的请求数,top100的时间点(精确到小时)

awk '{print $4}' access.log |cut -c 14-15|sort|uniq -c|sort -nr|head -n 100

性能分析

在nginx log中最后一个字段加入$request_time

列出传输时间超过 3 秒的页面,显示前20条

cat access.log|awk '($NF > 3){print $7}'|sort -n|uniq -c|sort -nr|head -20

列出php页面请求时间超过3秒的页面,并统计其出现的次数,显示前100条

cat access.log|awk '($NF > 1 && $7~/.php/){print $7}'|sort -n|uniq -c|sort -nr|head -100

蜘蛛抓取统计

统计蜘蛛抓取次数

grep 'Baiduspider' access.log |wc -l

统计蜘蛛抓取404的次数

grep 'Baiduspider' access.log |grep '404' | wc -l

TCP连接统计

查看当前TCP连接数

netstat -tan | grep "ESTABLISHED" | grep ":80" | wc -l

用tcpdump嗅探80端口的访问看看谁最高

tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr

Saltstack批量编译部署Nginx(多模块)

最近一直在研究saltstack的同步文件和批量执行命令,随着架构的变大,批量部署的需求也变得明显起来了,我需要用一条命令就部署好nginx和tomcat,并且符合我所有的环境需求,可以直接投入生产环境使用,这就需要用到saltstack的批量安装部署功能了。这篇文章主要介绍nginx的批量部署,下篇讲解tomcat多实例的批量部署方法。

环境介绍:

  • CentOS 6.5

  • salt 2015.5.10

  • nginx 1.12.0

  • minion:test

1、修改master配置文件,修改后重启服务,因为saltstack是用python写的,所以所有配置文件缩进和空格必须和文中一致!

mkdir -p /srv/salt
vim /etc/salt/master
  file_roots:    #前面必须有俩空格,下面缩进同理    
    base:      
      - /srv/salt/

2、主入口文件top.sls

vim /srv/salt/top.sls
 base:    
   'test':    #只作用于test这台minion      
     - nginx.init    #使用nginx下的init.sls文件进行初始化

3、创建nginx目录

mkdir -p /srv/salt/nginx/files    #用于存放模块和配置文件

mkdir -p /srv/salt/soft/    #用于存放模块的安装方法

cd /srv/salt/nginx && tree

未分类

4、编辑初始化文件init.sls

vim /srv/salt/nginx/init.sls
 include:  
   - nginx.install    #包含nginx下的install.sls

5、编辑安装部署文件install.sls

vim /srv/salt/nginx/install.sls
include:
  - soft.modules        #包含模块配置文件
#nginx.tar.gz
nginx_source:
  file.managed:
    - name: /tmp/nginx-1.12.0.tar.gz        #标识文件所在位置
    - unless: test -e /tmp/nginx-1.12.0.tar.gz    #检测文件是否存在,只在第一次检测
    - source: salt://nginx/files/nginx-1.12.0.tar.gz    #把maser上的文件传过去
#extract
extract_nginx:
  cmd.run:
    - cwd: /tmp        #进入/tmp目录
    - names:
      - tar zxvf nginx-1.12.0.tar.gz        #解压
    - unless: test -d /tmp/nginx-1.12.0.tar.gz
    - require:
      - file: nginx_source        #这个命令必须在上面的函数执行成功后才继续执行
#user
nginx_user:
  user.present:        #用户创建
    - name: nginx
    - createhome: False        #不用家目录
    - gid_from_name: True
    - shell: /sbin/nologin        #指定shell
#nginx_pkgs
nginx_pkg:
  pkg.installed:        #安装必备组件
    - pkgs:
      - gcc
      - gcc-c++
      - epel-release
      - openssl-devel
      - pcre-devel
      - zlib-devel
      - gd-devel
      - lua-devel
#nginx_compile
nginx_compile:        #nginx进行编译
  cmd.run:
    - cwd: /tmp/nginx-1.12.0
    - names:
      - ./configure --prefix=/usr/local/nginx  --user=nginx  --group=nginx --with-file-aio
       --with-http_ssl_module --with-http_realip_module --with-http_addition_module 
       --with-http_image_filter_module --with-http_gzip_static_module 
       --with-http_stub_status_module --with-mail --with-mail_ssl_module 
       --with-pcre --with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib 
       --with-http_sub_module --add-module=/soft/ngx_cache_purge-2.3 
       --add-module=/soft/ngx_devel_kit-0.3.0rc1 
       --add-module=/soft/echo-nginx-module-master 
       --add-module=/soft/lua-nginx-module-master && make && make install
    - require:
      - cmd: extract_nginx
      - pkg:  nginx_pkg
    #- unless: test -d /usr/local/nginx/    #检测或不检测目录是否存在
#cache_dir
cache_dir:
  cmd.run:
    - names:        #创建虚拟主机目录,把nginx目录权限给相关用户
      - mkdir -p /usr/local/nginx/conf/vhosts && chown -R nginx.nginx /usr/local/nginx/
    - require:
      - cmd: nginx_compile
    - unless: test -d /usr/local/nginx/conf/vhosts/
  #vhosts
  file.managed:
    - name: /usr/local/nginx/conf/nginx.conf    #修改后的配置文件复制过去
    - source: salt://nginx/files/nginx.conf
    #- unless: test -e /usr/local/nginx/conf/nginx.conf    #建议不进行检测,如果检测,有这个文件将不会进行更新

/usr/local/nginx/conf/proxy.conf:
  file.managed:
    - name: /usr/local/nginx/conf/proxy.conf
    - source: salt://nginx/files/proxy.conf
    #- unless: test -e /usr/local/nginx/conf/proxy.conf

6、编辑模块配置文件

vim /srv/salt/soft/modules.sls
echo-install:        #每个文件管理必须配置不同的名字,缩进必须一致,name:和source:后面的空格必须有!
  file.managed:
    - name: /soft/echo-nginx-module-master.zip
    - source: salt://nginx/files/echo-nginx-module-master.zip
    - user: root        #用户指定可有可无
    - group: root
    - mode: 755        #权限指定可有可无

  cmd.run:
    - name: cd /soft && unzip echo-nginx-module-master.zip
    - unless: test -d /soft/echo-nginx-module-master

lua-install:
  file.managed:
    - name: /soft/lua-nginx-module-master.zip
    - source: salt://nginx/files/lua-nginx-module-master.zip

  cmd.run:
    - name: cd /soft && unzip lua-nginx-module-master.zip
    - unless: test -d /soft/lua-nginx-module-master

purge-install:
  file.managed:
    - name: /soft/ngx_cache_purge-2.3.tar.gz
    - source: salt://nginx/files/ngx_cache_purge-2.3.tar.gz

  cmd.run:
    - name: cd /soft && tar xvf ngx_cache_purge-2.3.tar.gz
    - unless: test -d /soft/ngx_cache_purge-2.3

devel-install:
  file.managed:
    - name: /soft/ngx_devel_kit-0.3.0rc1.tar.gz
    - source: salt://nginx/files/ngx_devel_kit-0.3.0rc1.tar.gz

  cmd.run:
    - name: cd /soft && tar xvf ngx_devel_kit-0.3.0rc1.tar.gz
    - unless: test -d /soft/ngx_devel_kit-0.3.0rc1

7、执行同步推送

salt 'test' state.highstate

观察是否全部为success,如果有fail,查看具体失败原因,解决问题后可继续推送。

Ansible实战之Nginx高可用代理LNMP-wordpress

实验环境:前端使用Nginx做代理服务器,静态资源经由缓存服务器,连接后端web集群,动态资源直接连接后端集群,可由Nginx代理或Varnish实现动静分离,web服务端连接PHP服务,从而更好的提供动态资源,将动态资源数据保存在Mysql关系型数据库上,且Mysql数据库使用主从复制的技术。为验证整体架构的准确性,故将wordpress应用搭建在web服务端,来验证构架的有效性。为了防止单点故障,前端的Nginx代理还使用了keepqlive技术来实现高可用从而达到增加网络的安全性能的目的。

实验拓展:为了增加可用性,可将web集群分为动静两类web 集群组,从来实现动静分离的效果,Varnish集群来为静态资源提供缓存,从而使网络访问速度更快。前端代理也可使用HAProxy及LVS等技术来替代。后端Mysql数据库也可以增加数据备份的案例。

varnish的分离分离参考 http://www.cnblogs.com/JevonWei/p/7499417.html

网络拓扑图
未分类

主机环境

Ansible         172.16.252.82
Nginx_A 代理  172.16.252.207  
Nginx_B 代理  172.16.252.103
Keepalived_A    172.16.252.207  
Keepalived_B    172.16.252.103
Nginx+PHP_A     172.16.252.184  
Nginx+PHP_B     172.16.252.67
Mysql_Master    172.16.252.184  
Mysql_Slave     172.16.252.67

受添加限制
    Nginx_A和Keepalived_A为Nginx1.danran.com上
    Nginx_B和Keepalived_B为Nginx2.danran.com上
    Nginx+PHP_A和Mysql_Mstart在web1.danran.com主机上
    Nginx+PHP_B和Mysql_Slave在web2.danran.com主机上

实验准备

  • 各节点需保持时间同步
  • 确保主机名可以通信
  • 节点间使用秘钥连接

时间同步

[root@ansible ~]# ntpdate 172.16.0.1

节点主机名通信

编辑/etc/hosts主机解析文件或使用DNS解析亦可

[root@ansible ~]# vim /etc/hosts
172.16.252.184  web1.danran.com
172.16.252.67   web2.danran.com
172.16.252.82   ansible.danran.com
172.16.252.103  nginx2.danran.com
172.16.252.82   Ansible.danran.com
[root@ansible ~]# scp /etc/hosts nginx1.danran.com:/etc/
[root@ansible ~]# scp /etc/hosts nginx2.danran.com:/etc/
[root@ansible ~]# scp /etc/hosts web1.danran.com:/etc/
[root@ansible ~]# scp /etc/hosts web2.danran.com:/etc/

节点秘钥连接

[root@ansible ~]# ssh-keygen -t rsa -P ""
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
8e:bb:44:d7:25:df:1b:3e:9b:fa:22:15:b5:6b:e4:19 root@ansible
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|              .  |
|          . .. . |
|         . +..E  |
|      . S . .+o+ |
|     . +    ..=o |
|      o .  . .+  |
|     . .  . .  + |
|      o.   ..++  |
+-----------------+
[root@ansible ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]
[root@ansible ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]
[root@ansible ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]
[root@ansible ~]# ssh-copy-id -i .ssh/id_rsa.pub [email protected]

Ansible配置文件

[root@ansible ~]# vim ansible.yml 
- hosts: websrvs
  remote_user: root
  roles:
  - nginx_web
- hosts: proxy
  remote_user: root
  roles:
  - nginx_proxy
- hosts: keepalive
  remote_user: root
  roles:
  - keepalive
- hosts: varnish
  remote_user: root
  roles:
  - varnish
- hosts: php-fpm
  remote_user: root
  roles:
  - php-fpm
- hosts: mysql
  remote_user: root
  roles:
  - mariadb
- hosts: websrvs
  remote_user: root
  roles:
  - wordpress 

Ansible主机清单文件

[root@ansible ~]# vim /etc/ansible/hosts 
[websrvs]
172.16.252.184
172.16.252.67

[proxy]
172.16.252.207
172.16.252.103

[keepalive]
172.16.252.207  start1=MASTER start2=BACKUP priority1=100 priority2=90
172.16.252.103  start1=BACKUP start2=MASTER priority1=90 priority2=100

[varnish]
172.16.252.207
172.16.252.103

[php-fpm]
172.16.252.184
172.16.252.67

[mysql]
172.16.252.184 serverid=1  log="log_bin = master-log"
172.16.252.67  serverid=2  log="relay-log = master-log"

定义角色

keepalive

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir keepalived/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim keepalive/tasks/main.yml 
- name: install keepalived
  yum: name=keepalived state=latest
- name: install conf
  template: src=keepalived.j2 dest=/etc/keepalived/keepalived.conf
  tags: conf
  notify: restart keepalived
- name: start keepalived
  service: name=keepalived state=started

[root@ansible roles]# vim keepalive/handlers/main.yml 
- name: restart keepalived
  service: name=keepalived state=restarted

[root@ansible roles]# vim keepalive/templates/keepalived.j2 
global_defs {
    notification_email {
        [email protected]
    }
    notification_email_from [email protected]
    smtp_server 127.0.0.1
    smtp_connect_timeout 30
    router_id keepaliveA
    vrrp_mcast_group4 224.103.5.5
}
vrrp_instance VI_A {
    state {{ start1 }}
    interface {{ ansible_default_ipv4.alias }}
    virtual_router_id 51
    priority {{ priority1 }}
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass qr8hQHuL
    }

    virtual_ipaddress {
    172.16.252.100/32
    }
}
vrrp_instance VI_B {
    state {{ start2 }}
    interface {{ ansible_default_ipv4.alias }}
    virtual_router_id 52
    priority {{ priority2 }}
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass eHTQgK0n
    }
    virtual_ipaddress {
       172.16.252.10/32
    }
}

nginx_web

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir nginx_web/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim nginx_web/tasks/main.yml 
- name: install nginx
  yum: name=nginx state=latest
  when: ansible_os_family == "RedHat"
- name: install conf
  template: src=vhost1.conf.j2 dest=/etc/nginx/conf.d/vhost1.conf
  tags: conf
  notify: restart nginx
- name: install site home directory
  file: path={{ ngxroot }} state=directory
- name: install index page
  copy: src=index.html dest={{ ngxroot }}/
- name: start nginx
  service: name=nginx state=started

[root@ansible roles]# vim nginx_web/handlers/main.yml 
- name: restart nginx
  service: name=nginx state=restarted

[root@ansible roles]# vim nginx_web/vars/main.yml 
ngxroot: /blog

[root@ansible roles]# vim nginx_web/templates/vhost1.conf.j2 
server {
    listen 8080;
    root "/blog/wordpress";
    index index.php index.html;
    location ~ .*.(php|php5)?$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}

nginx_proxy

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir nginx_proxy/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim nginx_proxy/tasks/main.yml 
- name: install nginx
  yum: name=nginx state=latest
  when: ansible_os_family == "RedHat"
- name: install conf
  template: src=proxy.conf.j2 dest=/etc/nginx/conf.d/vhost1.conf
  tags: conf
  notify: restart nginx
- name: install nginx.conf
  copy: src=nginx.conf  dest=/etc/nginx/nginx.conf
- name: start nginx
  service: name=nginx state=started

[root@ansible roles]# vim nginx_proxy/handlers/main.yml 
- name: restart nginx
  service: name=nginx state=restarted

[root@ansible roles]# vim nginx_proxy/templates/proxy.conf.j2 
upstream websrv {
    server 172.16.252.207:6081;
    server 172.16.252.103:6081;
}

server {
    listen 80 default_server;
    server_name www.jevon.com;
    location / {
        proxy_pass http://websrv/;
        proxy_set_header Host $host;
        proxy_set_header X-Forward-For $remote_addr;
    }
}

[root@ansible roles]# vim nginx_proxy/files/nginx.conf  \取消nginx自带默认web主机,将新定义的web虚拟主机作为默认主机
server {
    listen       80 ;
}

varnish

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir varnish/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim varnish/tasks/main.yml 
- name: install varnish
  yum: name=varnish state=latest
- name: install conf
  copy: src=default.vcl dest=/etc/varnish/
  tags: varconf
  notify: restart varnish
- name: start varnish
  service: name=varnish state=started

[root@ansible roles]# vim varnish/handlers/main.yml 
- name: restart varnish
  service: name=varnish  state=restarted

[root@ansible roles]# vim varnish/files/default.vcl 
vcl 4.0;
import directors;
backend web1 {
.host = "172.16.252.184";
.port = "8080";
}
backend web2 {
    .host = "172.16.252.67";
    .port = "8080";
}
sub vcl_init {
    new websrv = directors.round_robin();
    websrv.add_backend(web1);
    websrv.add_backend(web2);
}

sub vcl_purge {
    return (synth(200,"Pruge Fishished"));
}
acl purges {
    "172.16.252.110";
    "127.0.0.0"/8;
}
sub vcl_recv {
    if (req.method == "PURGE") {
        if (client.ip !~ purges) {
            return(synth(403,"Purging not allowed for" + client.ip));
    }
    return(purge);
}
    if (req.url ~ "(?i).(jpg|jpeg|png|gif)$") {
        set req.backend_hint = websrv.backend();
     }else {
        set req.backend_hint = websrv.backend();
    }
    if (req.restarts == 0) {
        if (req.http.X-Forwarded-For) {
            set req.http.X-Forwarded-For = req.http.X-Forwarded-For + "," + client.ip;
        } else {
                set req.http.X-Forwarded-For = client.ip;
        }
    }
}
sub vcl_backend_response {
    unset beresp.http.X-Powered-By;
    if (bereq.url ~ ".(css|js|png|gif|jp(e?)g|swf|ico|txt|eot|svg|woff)") {
    unset beresp.http.cookie;
    set beresp.http.cache-control = "public, max-age=3600";
    }
    if ( beresp.status != 200 && beresp.status != 404 ) {
        set beresp.uncacheable = true;
        set beresp.ttl = 120s;
        return (deliver);
    }
    set beresp.ttl = 1h;
    set beresp.grace = 30s;
    return (deliver);
}
sub vcl_deliver {
    if (obj.hits>0) {
        set resp.http.X-Cache = "Hit Via " + server.ip;
    } else {
        set resp.http.X-Cache = "Miss from " + server.ip;
    }
}

php-fpm

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir php-fpm/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim php-fpm/tasks/main.yml 
- name: install {{ item }} package
  yum: name={{ item }} state=latest
  with_items:
  - php-fpm
  - php-mysql
- name: start php-fpm
  service: name=php-fpm  state=started  enabled=yes

mariadb

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir mariadb/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim mariadb/tasks/main.yml 
- name: install mariadb
  yum: name=mariadb-server   state=latest
- name: install conf
  template: src=server.j2 dest=/etc/my.cnf.d/server.cnf
  tags: conf
  notify: restart mariadb
- name: start mariadb
  service: name=mariadb  state=started  enabled=yes
- name: command master
  shell: /usr/bin/mysql -e "GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repluser'@'172.16.%.%' IDENTIFIED BY 'replpass';"
  shell: /usr/bin/mysql -e "flush privileges;"
  when: ansible_hostname == "web1"
- name: command slave
  shell: /usr/bin/mysql -e "CHANGE MASTER TO MASTER_HOST='172.16.252.184', MASTER_USER='repluser', MASTER_PASSWORD='replpass', MASTER_LOG_FILE='master-log.000003', MASTER_LOG_POS=245;"
  shell: /usr/bin/mysql -e "start slave;"
  when: ansible_hostname == "web2"
- name: wordpress command
  shell: /usr/bin/mysql -e "create database blog;"
  shell: /usr/bin/mysql -e "grant all on blog.* to 'blog'@'localhost' identified by 'blog';"

[root@ansible roles]# vim mariadb/handlers/main.yml 
- name: restart mariadb
  service: name=mariadb state=restarted

[root@ansible roles]# vim mariadb/templates/server.j2 
[mysqld]

server-id = {{ serverid }}
{{ log }}
innodb_file_per_table = ON
skip_name_resolve = ON

wordpress

[root@ansible ~]# cd /etc/ansible/roles/
[root@ansible ~]# mkdir wordpress/{files,templates,tasks,handlers,vars,meta,default} -pv

[root@ansible roles]# vim wordpress/tasks/main.yml 
- name: install unzip
  yum: name=unzip state=latest
- name: copy file
  copy: src=wordpress-4.8.1-zh_CN.zip dest=/blog
- name: command unzip
  command: /usr/bin/unzip -o  /blog/wordpress-4.8.1-zh_CN.zip -d /blog
- name: copy conf
  copy: src=wp-config.php dest=/blog/wordpress/
- name: mv conf
  command: mv /blog/wordpress/wp-config-sample.php /blog/wordpress/wp-config.php
  command: sed -ri 's/database_name_here/blog/' /blog/wordpress/wp-config.php
  command: sed -ri 's/username_here/blog/' /blog/wordpress/wp-config.php
  command: sed -ri 's/password_here/blog/' /blog/wordpress/wp-config.php

[root@ansible roles]# ls wordpress/files/
wordpress-4.8.1-zh_CN.zip

运行yml样本

[root@ansible ~]# ansible-playbook ansible.yml 
    .....
    .....
PLAY RECAP *********************************************************************
172.16.252.103             : ok=15   changed=4    unreachable=0    failed=0   
172.16.252.184             : ok=20   changed=3    unreachable=0    failed=0   
172.16.252.207             : ok=14   changed=2    unreachable=0    failed=0   
172.16.252.67              : ok=20   changed=3    unreachable=0    failed=0  

访问测试

未分类

CentOS 7 下编译Nginx并打包成rpm

上次说的,最近喜欢上了折腾Nginx。作为一个Web从业人员,越来越觉得Nginx太强大了。

于是便花了几天时间研究在Debian及CentOS下从源代码开始将Nginx打包成deb/rpm,这篇是记录CentOS 7 下将Nginx打包成rpm。

安装软件之前肯定是先要更新:

yum update

安装编译环境:

yum install gcc gcc-c++ rpm-build

安装Nginx所依赖的包:

yum install -y openssl-devel zlib-devel pcre-devel gd-devel

新建用户:

name=rpmbuild

useradd $name

echo "$name ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

su - $name

进入SOURCES目录:

cd ~/SOURCES/

在新建的用户home目录创建接下来要用到的几个文件夹:

rpmdev-setuptree

这样在rpmbuild的home目录下面有了这几个目录:

BUILD BUILDROOT RPMS SOURCES SPECS SRPMS

到这个地址找到合适的源码包下载: nginx package

下载源码,当前(2016-06-16)最新为nginx-1.10.1-1.el7.ngx.src.rpm:

wget http://nginx.org/packages/centos/7/SRPMS/nginx-1.10.1-1.el7.ngx.src.rpm

解压:

rpm2cpio nginx-1.10.1-1.el7.ngx.src.rpm |cpio -dvi

里面应该有这么些个文件:

[root@790fde35905f SOURCES]# ls
COPYRIGHT nginx-debug.sysconf nginx.sysconf
logrotate nginx.conf nginx.upgrade.sh
nginx-1.10.1 nginx.init.in nginx.vh.default.conf
nginx-1.10.1-1.el7.ngx.src.rpm nginx.service njs-1c50334fbea6.tar.gz
nginx-1.10.1.tar.gz nginx.spec
nginx-debug.service nginx.suse.logrotate

开始编译:

rpmbuild -ba nginx.spec

如果没有意外的话,在~/rpmbuild/RPMS/x86_64下面应该生成了对应的rpm包:

nginx-1.10.1-1.el7.centos.ngx.x86_64.rpm
nginx-debuginfo-1.10.1-1.el7.centos.ngx.x86_64.rpm
nginx-module-geoip-1.10.1-1.el7.centos.ngx.x86_64.rpm
nginx-module-image-filter-1.10.1-1.el7.centos.ngx.x86_64.rpm
nginx-module-njs-1.10.1.0.0.20160414.1c50334fbea6-1.el7.centos.ngx.x86_64.rpm
nginx-module-perl-1.10.1-1.el7.centos.ngx.x86_64.rpm
nginx-module-xslt-1.10.1-1.el7.centos.ngx.x86_64.rpm

上面是按照Nginx默认的configure配置打包成的rpm,既然选择了自主打包而不是使用Nginx官方打包好的rpm,肯定是有些模块Nginx打包的不包含,自主打包也就是想把我们需要的模块加进Nginx而又不想在生产服务器安装一大堆包,所以,为了加进我们所需要的模块,我们可以更改上面哪个nginx.spec文件,加进我们所需要的模块,怎么加进去可以参考我先前的一篇文章Debian 8 下编译Nginx笔记。

进过我实际编译,暂时发现我所需要的两个额外模块Google Filter和PageSpeed中Google Filter可以正常编译进去,但是PageSpeed会报错,暂时没找到解决办法,有时间我再折腾一下。

CentOS6.5使用yum命令方便快捷安装Nginx

1、默认 yum 仓库无法直接安装nginx,需要创建一个文件

/etc/yum.repos.d/nginx.repo,并将下面的内容复制进去: 
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

2、编辑并保存/etc/yum.repos.d/nginx.repo文件后,在命令行下执行

[root@localhost ~]# yum list | grep nginx
nginx.x86_64                               1.8.0-1.el6.ngx             nginx    
nginx-debug.x86_64                         1.8.0-1.el6.ngx             nginx    
nginx-debuginfo.x86_64                     1.8.0-1.el6.ngx             nginx    
nginx-nr-agent.noarch                      2.0.0-8.el6.ngx             nginx

安装:yum -y install nginx

nginx支持sub_filter的方法

这是一个基础的方法,网上的一些文章有些坑,这里整理一下,只适合新手看的

第1步:

wget http://nginx.org/download/nginx-1.9.9.tar.gz

第2步:

tar xf nginx-1.9.9.tar.gz

第3步:

cd nginx-1.9.9

第4步:

git clone git://github.com/yaoweibin/ngx_http_substitutions_filter_module.git

第5步:

yum -y install gcc gcc-c++ autoconf automake make pcre-devel openssl openssl-devel

第6步:

./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module  --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --add-module=./ngx_http_substitutions_filter_module

第7步:

make
make install

第8步 配置

server {
    listen       81;
    server_name  localhost;
    location / {
          proxy_pass http://172.16.203.254/;
          proxy_set_header Accept-Encoding ‘’;
          sub_filter_once off;
          sub_filter </body>  ‘<script src=“http://172.16.41.1:81/codeview/codeview.js”></script></body>’;
    }
}

阿里云centos7.3编译安装NGINX+PHP7+MariaDB+MEMCACHED

一、安装前准备

  • 修改默认主机名称
[root@iZuf60c5bxd15kr9gycvv6Z ~]# hostnamectl set-hostname centos7
[root@iZuf60c5bxd15kr9gycvv6Z ~]# reboot
[root@iZuf60c5bxd15kr9gycvv6Z ~]# yum update
  • 安装依赖库
[root@centos7 ~]# yum -y install libaio libaio-devel bison bison-devel zlib-devel openssl openssl-devel ncurses ncurses-devel libcurl-devel libarchive-devel boost boost-devel lsof wget gcc gcc-c++ make cmake perl kernel-headers kernel-devel pcre-devel

二、删除系统默认数据库配置文件

  • 查询
[root@centos7 ~]# find -H /etc/ | grep my.c
/etc/my.cnf
/etc/my.cnf.d
/etc/my.cnf.d/mysql-clients.cnf
/etc/pki/tls/certs/renew-dummy-cert
/etc/pki/tls/certs/make-dummy-cert
  • 删除
[root@centos7 ~]# rm -rf /etc/my.cnf /etc/my.cnf.d /etc/my.cnf.d/mysql-clients.cnf
  • 确认
[root@centos7 ~]# find -H /etc/ | grep my.c
/etc/pki/tls/certs/renew-dummy-cert
/etc/pki/tls/certs/make-dummy-cert

三、卸载系统自带mariadb-libs

  • 查询
[root@centos7 ~]# rpm -qa|grep mariadb-libs
mariadb-libs-5.5.52-1.el7.x86_64
  • 删除
[root@centos7 ~]# rpm -e mariadb-libs-5.5.52-1.el7.x86_64 --nodeps

四、安装MariaDB数据库

  • 下载安装包
[root@centos7 ~]# cd /usr/local/src
[root@centos7 src]# wget https://downloads.mariadb.org/interstitial/mariadb-10.2.8/source/mariadb-10.2.8.tar.gz 
  • 解压
[root@centos7 src]# tar -zxvf mariadb-10.2.8.tar.gz
  • 创建数据库安装目录,数据存放目录,以及用户组、用户
# 创建mysql用户组
[root@centos7 mariadb-10.2.8]# groupadd -r mysql
# 创建mysql用户
[root@centos7 mariadb-10.2.8]# useradd -r -g mysql -s /sbin/nologin -d /usr/local/mysql -M mysql
# 创建安装目录
[root@centos7 mariadb-10.2.8]# mkdir -p /usr/local/mysql
# 创建数据存放目录
[root@centos7 mariadb-10.2.8]# mkdir -p /data/mysql
# 赋以mysql用户读写权限
[root@centos7 mariadb-10.2.8]# chown -R mysql:mysql /data/mysql
  • 编译安装
[root@centos7 mariadb-10.2.8]# cd /usr/local/src/mariadb-10.2.8
# 输入以下编译参数
cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql 
-DMYSQL_DATADIR=/data/mysql 
-DSYSCONFDIR=/etc 
-DWITHOUT_TOKUDB=1 
-DWITH_INNOBASE_STORAGE_ENGINE=1 
-DWITH_ARCHIVE_STPRAGE_ENGINE=1 
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 
-DWIYH_READLINE=1 
-DWIYH_SSL=system 
-DVITH_ZLIB=system 
-DWITH_LOBWRAP=0 
-DMYSQL_UNIX_ADDR=/tmp/mysql.sock 
-DDEFAULT_CHARSET=utf8 
-DDEFAULT_COLLATION=utf8_general_ci

# 如果编译失败请删除CMakeCache.txt
[root@centos7 mariadb-10.2.8]# rm -f CMakeCache.txt
# 让指令重新执行,否则每次读取这个文件,命令修改正确也是报错
# cmake没问题,可以编译并且安装了

# 开始安装,这个过程比较久,跟据电脑配制不同可能会有10-30分钟
[root@centos7 mariadb-10.2.8]# make && make install
  • 导入mysql系统表
[root@centos7 mariadb-10.2.8]# cd /usr/local/mysql/
[root@localhost mysql]# scripts/mysql_install_db --user=mysql --datadir=/data/mysql
  • 复制配制文件
[root@localhost ~]# cd /usr/local/mysql/
[root@localhost mysql]# cp support-files/my-large.cnf /etc/my.cnf
  • 编写快捷启动脚本
[root@centos7 mysql]# vi /lib/systemd/system/mysql.service
# --------------------------------------------------------------------------
# 输入以下代码
# --------------------------------------------------------------------------
[Unit]
Description=MySQL Community Server
After=network.target

[Service]
User=mysql
Group=mysql
Type=forking
PermissionsStartOnly=true
PIDFile=/data/mysql/centos7.pid
ExecStart=/usr/local/mysql/support-files/mysql.server start
ExecReload=/usr/local/mysql/support-files/mysql.server restart
ExecStop=/usr/local/mysql/support-files/mysql.server stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • 设置开机启动
[root@centos7 mysql]# systemctl enable mysql.service
  • 其它命令说明
# 启动mysql
[root@centos7 mysql]# systemctl start mysql.service
# 停止mysql
[root@centos7 mysql]# systemctl stop mysql.service
# 重启mysql
[root@centos7 mysql]# systemctl restart mysql.service
# 如果提示:Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.
# 请选结束mysql进程后再尝试执行上面的快捷操作
[root@centos7 mysql]# pkill -9 mysql
  • 配置环境变量(以便在任何目录下输入mysql命令)
# 创建独立环境变量文件
[root@localhost mysql]# touch /etc/profile.d/mysql.sh
# 写入变量值
[root@localhost mysql]# echo 'export PATH=$PATH:/usr/local/mysql/bin/' > /etc/profile.d/mysql.sh 
# 赋以执行权限
[root@localhost mysql]# chmod 0777 /etc/profile.d/mysql.sh 
# 刷新生效
[root@localhost mysql]# source /etc/profile.d/mysql.sh
  • 初始化MariaDB
# 运行MariaDB初始化脚本
[root@localhost mysql]# ./bin/mysql_secure_installation

# --------------------------------------------------------------------------
# 根据相关提示进行操作
# 以下提示:
# --------------------------------------------------------------------------
Enter current password for root (enter for none):    输入当前root密码(没有输入)
Set root password? [Y/n]                             设置root密码?(是/否)
New password:                                        输入新root密码
Re-enter new password:                               确认输入root密码
Password updated successfully!                       密码更新成功
Remove anonymous users? [Y/n]                        删除匿名用户?(是/否)
Disallow root login remotely? [Y/n]                  不允许root登录远程?(是/否)
Reload privilege tables now? [Y/n]                   现在重新加载权限表(是/否)

#全部完成!如果你已经完成了以上步骤,MariaDB安装现在应该安装完成。
  • 创建外部管理员帐号(根据需要,请尽量保证密码的复杂性避免数据库外泄)
[root@localhost mysql] mysql -uroot -p
# 根据提示输入密码
MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;

五、安装NGINX

  • 下载安装包并解压
[root@localhost mysql]# cd /usr/local/src
[root@localhost src]# wget http://nginx.org/download/nginx-1.12.1.tar.gz
[root@localhost src]# tar -zxvf nginx-1.12.1.tar.gz
  • 创建NGINX安装目录,WEB存放目录,以及用户组、用户
# 创建nginx用户组
[root@centos7 src]# groupadd -r www
# 创建nginx用户
[root@centos7 src]# useradd -r -g www -s /sbin/nologin -d /usr/local/nginx -M www
# 创建安装目录
[root@centos7 src]# mkdir -p /usr/local/nginx
# 创建数据存放目录
[root@centos7 src]# mkdir -p /data/web
# 赋以mysql用户读写权限
[root@centos7 src]# chown -R www:www /data/web
  • 编译安装
[root@localhost src]# cd nginx-1.12.1
# 输入以下参数
./configure 
--prefix=/usr/local/nginx 
--without-http_memcached_module 
--user=www  
--group=www 
--with-http_stub_status_module 
--with-http_ssl_module 
--with-http_gzip_static_module

# 如果看到以下说明则编译成功
Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

# 开始安装
[root@localhost nginx-1.12.1]# make && make install
  • 尝试启动
[root@centos7 nginx-1.12.1]# /usr/local/nginx/sbin/nginx
# 如果未提示错误即代表安装成功
  • 编写快捷启动脚本
[root@centos7 nginx-1.12.1]# vi /lib/systemd/system/nginx.service
# --------------------------------------------------------------------------
# 输入以下代码
# --------------------------------------------------------------------------
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • 设置开机启动
[root@centos7 nginx-1.12.1]# systemctl enable nginx.service
  • 其它命令说明
# 启动nginx
[root@centos7 nginx-1.12.1]# systemctl start nginx.service
# 停止nginx
[root@centos7 nginx-1.12.1]# systemctl stop nginx.service
# 重启nginx
[root@centos7 nginx-1.12.1]# systemctl restart nginx.service
# 如果提示:Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
# 请选结束nginx进程后再尝试执行上面的快捷操作
[root@centos7 nginx-1.12.1]# pkill -9 nginx
  • 修改配NGINX配制文件
[root@centos7 php-7.1.9]# cd /usr/local/nginx/conf
[root@centos7 conf]# vi nginx.conf
# 修改如下代码
# --------------------------------------------------------------------------
#user  nobody;去除前面#号,并将用户改为www www
user www www;
# --------------------------------------------------------------------------
#pid        logs/nginx.pid; 去除前面的#号 
pid        logs/nginx.pid;
# --------------------------------------------------------------------------
去除前面的#号 如下
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';
# --------------------------------------------------------------------------
# gzip  on;去除前面的#号并加上隐藏版号代码 
server_tokens off;
# --------------------------------------------------------------------------
index  index.html index.htm;后面加上index.php 默认页
index  index.html index.htm index.php;
# --------------------------------------------------------------------------
去下以下前面的#号并做如下修改
location ~ .php$ {
    root           html;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
}
  • 最后张节介绍虚拟主机配制,以及memcache配制

七、安装PHP7

  • 下载安装包并解压
[root@centos7 nginx-1.12.1]# cd /usr/local/src
[root@centos7 src]# wget http://cn.php.net/distributions/php-7.1.9.tar.gz
[root@centos7 src]# tar -zxvf php-7.1.9.tar.gz
  • 安装必要的相关扩展
[root@centos7 src]# yum install libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel libcurl libcurl-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel
  • 编译安装
[root@localhost src]# cd php-7.1.9
# 输入以下参数
./configure 
--prefix=/usr/local/php 
--with-config-file-path=/usr/local/php/etc 
--enable-fpm 
--with-fpm-user=www  
--with-fpm-group=www 
--enable-inline-optimization 
--disable-debug 
--disable-rpath 
--enable-shared  
--enable-soap 
--with-libxml-dir 
--with-xmlrpc 
--with-openssl 
--with-mcrypt 
--with-mhash 
--with-pcre-regex 
--with-zlib 
--enable-bcmath 
--with-iconv 
--with-bz2 
--enable-calendar 
--with-curl 
--with-cdb 
--enable-dom 
--enable-exif 
--enable-fileinfo 
--enable-filter 
--with-pcre-dir 
--enable-ftp 
--with-gd 
--with-openssl-dir 
--with-jpeg-dir 
--with-png-dir 
--with-zlib-dir  
--with-freetype-dir 
--enable-gd-native-ttf 
--enable-gd-jis-conv 
--with-gettext 
--with-gmp 
--with-mhash 
--enable-json 
--enable-mbstring 
--enable-mbregex 
--enable-mbregex-backtrack 
--with-libmbfl 
--with-onig 
--enable-pdo 
--with-mysqli=mysqlnd 
--with-pdo-mysql=mysqlnd 
--with-zlib-dir 
--with-pdo-sqlite 
--with-readline 
--enable-session 
--enable-shmop 
--enable-simplexml 
--enable-sockets  
--enable-sysvmsg 
--enable-sysvsem 
--enable-sysvshm 
--enable-wddx 
--with-libxml-dir 
--with-xsl 
--enable-zip 
--enable-mysqlnd-compression-support 
--with-pear 
--enable-opcache

# 开始安装
[root@localhost php-7.1.9]# make && make install
  • 配置环境变量(以便在任何目录下输入php命令)
# 创建独立环境变量文件
[root@localhost php-7.1.9]# touch /etc/profile.d/php.sh
# 写入变量值
[root@localhost php-7.1.9]# echo 'export PATH=$PATH:/usr/local/php/bin/' > /etc/profile.d/php.sh 
# 赋以执行权限
[root@localhost php-7.1.9]# chmod 0777 /etc/profile.d/php.sh 
# 刷新生效
[root@localhost php-7.1.9]# source /etc/profile.d/php.sh
  • 配制php.ini
[root@centos7 php-7.1.9]# cp php.ini-production /usr/local/php/etc/php.ini
[root@centos7 php-7.1.9]# vi /usr/local/php/etc/php.ini
# 做以下修改(时区,不显示版本号,开启opcache缓存加速PHP)
# --------------------------------------------------------------------------
1.找到:;date.timezone =                               修改为:date.timezone = PRC
2.找到:expose_php = On                                   修改为:expose_php = Off
3.找到:opcache.enable=0                              修改为:opcache.enable=1
4.在 Dynamic Extensions 代码块中添加 zend_extension=opcache.so
  • 配置php-fpm
[root@centos7 php-7.1.9]# cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
[root@centos7 php-7.1.9]# cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
[root@centos7 php-7.1.9]# cp sapi/fpm/init.d.php-fpm /usr/local/php/bin/php-fpm
[root@centos7 php-7.1.9]# chmod 0777 /usr/local/php/bin/php-fpm
  • 尝试启动
[root@centos7 php-7.1.9]# /usr/local/php/bin/php-fpm start
Starting php-fpm  done
# 如提示以上即表示安装成功
  • 编写快捷启动脚本
[root@centos7 php-7.1.9]# vi /lib/systemd/system/php-fpm.service
# --------------------------------------------------------------------------
# 输入以下代码
# --------------------------------------------------------------------------
[Unit]
Description=php-fpm
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/php/var/run/php-fpm.pid
ExecStart=/usr/local/php/bin/php-fpm start
ExecReload=/usr/local/php/bin/php-fpm restart
ExecStop=/usr/local/php/bin/php-fpm stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • 设置开机启动
[root@centos7 php-7.1.9]# systemctl enable php-fpm.service
  • 其它命令说明
# 启动php-fpm
[root@centos7 php-7.1.9]# systemctl start php-fpm.service
# 停止php-fpm
[root@centos7 php-7.1.9]# systemctl stop php-fpm.service
# 重启php-fpm
[root@centos7 php-7.1.9]# systemctl restart php-fpm.service
# 如果提示:Job for php-fpm.service failed because the control process exited with error code. See "systemctl status php-fpm.service" and "journalctl -xe" for details.
# 请选结束php-fpm进程后再尝试执行上面的快捷操作
[root@centos7 php-7.1.9]# pkill -9 php-fpm

八、NGINX虚拟主机配制

  • 打开配制文件
[root@centos7 php-7.1.9]# vi /usr/local/nginx/conf/nginx.conf
  • 在http{}节点尾加入以下代码
    ##############################################
    #LIANGZHI
    ##############################################
    server {
        listen          80;
        server_name     *.demo.com;
        root            /data/web/demo/www;
        access_log      /data/web/demo/log/access.log  main;
        error_log       /data/web/demo/log/error.log error;
        index           index.php;

        #THINKPHP伪静态
        location / {
            if (!-e $request_filename) {
                rewrite ^(.*)$ /index.php?s=$1 last;
                break;
            }
        }

        #解析PHP代码
        location ~ .php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        #静态资源缓存1天
        location ~ .*.(gif|jpg|jpeg|png|bmp|ico|swf|js|css)$ {
            expires     1d;
            access_log  off;
        }

        #字体文件跨域问题
        location ~ .*.(eof|ttf|ttc|otf|eof|woff|woff2|svg)(.*){
            add_header Access-Control-Allow-Origin *;
        }
    }

九、安装PHP支持插件Memcache

[root@centos7 www]# cd /usr/local/src
[root@centos7 src]# wget http://memcached.org/files/memcached-1.5.1.tar.gz
[root@centos7 src]# tar -zxvf memcached-1.5.1.tar.gz
[root@centos7 src]# cd memcached-1.5.1
[root@centos7 memcached-1.5.1]# yum install libevent*
[root@centos7 memcached-1.5.1]# ./configure --prefix=/usr/local/memcached
[root@centos7 memcached-1.5.1]# make && make install
  • 编写快捷启动脚本
[root@centos7 memcached-1.5.1]# vi /usr/local/memcached/memcached
# 输入以下代码(启动参数请在下面的脚本中修改,如端口,最大内存)
#! /bin/sh
#
# chkconfig: - 55 45
# description:  The memcached daemon is a network memory cache service.
# processname: memcached
# config: /etc/sysconfig/memcached

# Source function library.
. /etc/rc.d/init.d/functions

PORT=11211
USER=root 
MAXCONN=1024
CACHESIZE=64
OPTIONS=""

if [ -f /etc/sysconfig/memcached ];then
    . /etc/sysconfig/memcached
fi

# Check that networking is up.
if [ "$NETWORKING" = "no" ]
then
    exit 0
fi

RETVAL=0

start () {
    echo "Starting memcached ..."
    # insure that /var/run/memcached has proper permissions
    chown $USER /usr/local/memcached/bin/memcached
    /usr/local/memcached/bin/memcached -d -p $PORT -u $USER -m $CACHESIZE -c $MAXCONN -P /var/run/memcached.pid $OPTIONS
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/memcached
}
stop () {
    echo "Stopping memcached ..."
    killproc memcached
    RETVAL=$?
    echo
    if [ $RETVAL -eq 0 ] ; then
        rm -f /var/lock/subsys/memcached
        rm -f /var/run/memcached.pid
    fi
}

restart () {
    stop
    start
}

# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
    stop
    ;;
    status)
    status memcached
    ;;
    restart|reload)
    restart
    ;;
    condrestart)
    [ -f /var/lock/subsys/memcached ] && restart || :
    ;;
    *)
    echo $"Usage: $0 {start|stop|status|restart|reload|condrestart}"
    exit 1
esac
  • 脚本执行权限
[root@localhost memcached-1.5.1]# chmod 0777 /usr/local/memcached/memcached
编写服务启动脚本
[root@centos7 memcached-1.5.1]# vi /lib/systemd/system/memcached.service
# --------------------------------------------------------------------------
# 输入以下代码
# --------------------------------------------------------------------------
[Unit]
Description=memcached
After=network.target

[Service]
Type=forking
PIDFile=/var/run/memcached.pid
ExecStart=/usr/local/memcached/memcached start
ExecReload=/usr/local/memcached/memcached restart
ExecStop=/usr/local/memcached/memcached stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • 设置开机启动
[root@centos7 memcached-1.5.1]# systemctl enable memcached.service
  • 其它命令说明
# 启动memcached
[root@centos7 memcached-1.5.1]# systemctl start memcached.service
# 停止memcached
[root@centos7 memcached-1.5.1]# systemctl stop memcached.service
# 重启memcached
[root@centos7 memcached-1.5.1]# systemctl restart memcached.service
# 如果提示:Job for memcached.service failed because the control process exited with error code. See "systemctl status memcached.service" and "journalctl -xe" for details.
# 请选结束memcached进程后再尝试执行上面的快捷操作
[root@centos7 memcached-1.5.1]# pkill -9 memcached
  • 为PHP增加memcache支持(官司网memcache-3.0.8暂时不支持PHP的编译)

官网memcache-3.0.8在编译的时候出现“php-smart_str.h”没有找到的错误!
但是我们可以在github里面找到pecl-memcache支持PHP7的分支,请按以下操作即可完成memcache中扩展安装

[root@centos7 memcached]# cd /usr/local/src/php-7.1.9/ext
# 如果已经安装git忽略yun install git
[root@centos7 memcached]# yum install git
[root@centos7 ext]# git clone https://github.com/websupport-sk/pecl-memcache memcache
[root@centos7 ext]# cd memcache
[root@centos7 ext]# yum install autoconf
[root@centos7 ext]# /usr/local/php/bin/phpize
[root@centos7 ext]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@centos7 ext]# make && make install
  • 修改php.ini
[root@centos7 ext]# vi /usr/local/php/etc/php.ini
# 在 Dynamic Extensions 代码块中添加如下扩展
extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20160303/memcache.so
  • 重启linux完成安装(或重启nginx php-fpm)
[root@centos7 ext]# reboot