最近入了一台独立服务器,如果直接拿来跑项目的话就太浪费资源了。于是打算使用Proxmox VE这款虚拟化管理软件进行VPS管理。

Proxmox VE是一款套开源的虚拟化管理软件,用户可通过网页的方式来管理服务器上使用 kvm 以及 lxc 技术运行的虚拟机。同时提供了一些先进功能的支持,如集群、HA等。

0x00 安装

Proxmox VE是基于Debian进行开发的,主要有两种安装方式。
其一是通过官方提供的iso作为一个全新的系统安装
另一种方式是在已有的Debian系统上安装
手动安装时请务必保证网卡配置正确,若出错的话在不带IPMI的机子上很难处理。

安装完成后即可通过https://ip:8006/访问管理页面

另外,这里记录一下版本升级的方法。由于Proxmox VE是一家商业公司在运营,所以一些功能是需要购买订阅才能使用的,例如说版本更新功能。但是可以通过一些方法绕过限制。注意这些更新方法请勿用于生产环境中。

将软件源更改为测试源

修改/etc/apt/sources.list.d/pve-install-repo.list, 将 pve-no-subscription 修改为pvetest
然后apt三连即可更新为新版本。

apt-get update
apt-get upgrade
apt-get dist-upgrade

0x01 相关设定

对于kvm虚拟化的虚拟机,若想上传需要用到的iso文件,可以直接通过网页端上传,也可以直接将文件放入/var/lib/vz/template/iso/
如果想对kvm虚拟机的启动参数进行调整,官方提供了api:qm set,具体可参照官方文档
对于lxc虚拟化的虚拟机,可以直接从系统中下载对应发行版的模板,无需自行下载。
可以直接使用LXC自带的api对lxc虚拟机进行管理,注意-n为虚拟机的id。

0x02 网络配置

对于多ip的服务器,本身官方就是按照桥接的方式做好网络配置的,直接在虚拟机中填写分配的ip即可。
对于单ip服务器,可以采用NAT的方法让虚拟机连上外部网络。这里介绍俩种方式。

采用QEMU自带的NAT

对于KVM虚拟机,可以直接在创建虚拟机的时候勾上NAT,这时候就会自动为虚拟机分配一个虚拟的子网并且虚拟机可以通过nat连接到外部网络,基本上是开箱即用。同时也支持端口映射,具体可参考官方wiki下的QEMU port redirection。但之前在使用的过程中,发现这个端口映射并不是很稳定。同时虽然这种方法很简单,但是虚拟机之间是隔离的,无法互通数据,这样就非常不灵活。
同时,LXC虚拟机是没有这种开箱即用的NAT的。

配置iptables创建子网以实现nat

主要思路是创建一个虚拟桥接设备并创建一个子网,然后将所有虚拟机包括宿主机都连接到这个子网内,再开启iptables的NAT功能。
编辑配置文件/etc/interfaces,以下是参考配置

nginx">auto vmbr2
iface vmbr2 inet static
    address 10.0.0.254
    netmask 255.255.255.0
    bridge_ports none
    bridge_stp off
    bridge_fd 0
    post-up echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up iptables -t nat -A POSTROUTING -s '10.0.0.0/24' -o vmbr0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '10.0.0.0/24' -o vmbr0 -j MASQUERADE

以上配置创建了vmbr2并且分配了一个子网10.0.0.0/24,同时宿主机(同时亦为网关)在这个子网内的ip为10.0.0.254。然后开启了内核的转发功能与iptables的NAT功能(其中vmbr0为通向外部网络的设备)。
若想添加端口转发直接在iptables中增加相关条目即可。
例如想要将宿主机vmbr0的80端口的tcp连接转发到10.0.0.102的80端口上:
iptables -t nat -A PREROUTING -i vmbr0 -p tcp --dport 80 -j DNAT --to 10.0.0.102:80
如果想保存转发规则,使之重启后依然有效,则需要在/etc/interfaces相应位置加入

post-up iptables -t nat -A PREROUTING -i vmbr0 -p tcp --dport 80 -j DNAT --to 10.0.0.102:80
post-down iptables -t nat -D PREROUTING -i vmbr0 -p tcp --dport 80 -j DNAT --to 10.0.0.102:80

通过以上方法就能组建一个灵活的子网了,kvm虚拟机和lxc虚拟机都可接入,并且都可以有端口转发。由于没有DHCP服务器所以要自行分配ip。注意创建虚拟机的时候将其挂载到vmbr2端口下。
我的服务器只有一个ip,所以内部组网就只能采取这种这种的方法了hhhh。为了充分利用资源,我将80,443端口转发到内部一台虚拟机上,这台虚拟机再使用nginx反代到内网的其它虚拟机,以充分利用单个ip。

启用BBR优化网络

目前的Proxmox VE版本的linux内核版本比较新,已经包含了bbr模块了。

修改sysctl.conf

echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf

保存生效

nginx">sysctl -p

检测是否已启用bbr模块

nginx">lsmod | grep bbr

如果含有bbr即说明内核内已启用bbr模块

Let's Encrypt作为一个公共且免费SSL的项目逐渐被广大用户传播和使用,是由Mozilla、Cisco、Akamai、IdenTrust、EFF等组织人员发起,主要的目的也是为了推进网站从HTTP向HTTPS过度的进程,目前已经有越来越多的商家加入和赞助支持。

Let's Encrypt免费SSL证书的出现,也会对传统提供付费SSL证书服务的商家有不小的打击。到目前为止,Let's Encrypt获得IdenTrust交叉签名,这就是说可以应用且支持包括FireFox、Chrome在内的主流浏览器的兼容和支持,虽然目前是公测阶段,但是也有不少的用户在自有网站项目中正式使用起来。

实战申请Let's Encrypt永久免费SSL证书过程教程及常见问题

在今年黑色星期五的时候,Namecheap各种促销活动中也包括年费0.88美元的SSL证书,当时老左也有购买了2个备用学习和适当的放到一些网站中看看效果(据说英文网站谷歌会很喜欢),当时冷雨同学就建议到时候直接使用Let's Encrypt免费SSL,毕竟有很多大公司支持的,比一些小公司提供的免费SSL证书靠谱很多。

虽然目前Let's Encrypt免费SSL证书默认是90天有效期,但是我们也可以到期自动续约,不影响我们的尝试和使用,为了考虑到文章的真实性和以后的实战性,老左准备利用一些时间分篇幅的展现在应用Let's Encrypt证书的过程,这篇文章分享申请的方法教程。

第一、安装Let's Encrypt前的准备工作

根据官方的要求,我们在VPS、服务器上部署Let's Encrypt免费SSL证书之前,需要系统支持Python2.7以上版本以及支持GIT工具。这个需要根据我们不同的系统版本进行安装和升级,因为有些服务商提供的版本兼容是完善的,尤其是debian环境兼容性比CentOS好一些。

比如CentOS 6 64位环境不支持GIT,我们还可以参考"Linux CentOS 6 64位系统安装Git工具环境教程"和"9步骤升级CentOS5系统Python版本到2.7"进行安装和升级。最为 简单的就是Debian环境不支持,可以运行"apt-get -y install git"直接安装支持,如果是CentOS直接运行"yum -y install git-core"支持。这个具体遇到问题在讨论和搜索解决方案,因为每个环境、商家发行版都可能不同。在这篇文章中,老左采用的是debian 7 环境。

第二、快速获取Let's Encrypt免费SSL证书

在之前的博文中老左也分享过几篇关于SSL部署的过程,我自己也搞的晕乎晕乎的,获取证书和布局还是比较复杂的,Let's Encrypt肯定是考虑到推广HTTPS的普及型会让用户简单的获取和部署SSL证书,所以可以采用下面简单的一键部署获取证书。

PS:在获取某个站点证书文件的时候,我们需要在安装PYTHON2.7以及GIT,更需要将域名解析到当前VPS主机IP中。

git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto certonly --standalone --email admin@laozuo.org -d laozuo.org -d www.laozuo.org

然后执行上面的脚本,我们需要根据自己的实际站点情况将域名更换成自己需要部署的。

快速获取Let's Encrypt免费SSL证书

看到这个界面,直接Agree回车。

Let's Encrypt安装成功

然后看到这个界面表示部署成功。目前根据大家的反馈以及老左的测试,如果域名是用的国内DNS,包括第三那方DNSPOD等,都可能获取不到域名信息。

Let's Encrypt国内域名DNS不支持

这里我们可以看到有"The server could not connect to the client to verify the  domain"的错误提示信息,包括也有其他提示错误,"The server experienced an internal error :: Error creating new registration"我们在邮局的时候不要用国内免费邮局。所以,如果我们是海外域名就直接先用域名自带的DNS。

第三、Let's Encrypt免费SSL证书获取与应用

在完成Let's Encrypt证书的生成之后,我们会在"/etc/letsencrypt/live/laozuo.org/"域名目录下有4个文件就是生成的密钥证书文件。

cert.pem  - Apache服务器端证书
chain.pem  - Apache根证书和中继证书
fullchain.pem  - Nginx所需要ssl_certificate文件
privkey.pem - 安全证书KEY文件

如果我们使用的Nginx环境,那就需要用到fullchain.pem和privkey.pem两个证书文件,在部署Nginx的时候需要用到(参考:LNMP一键包环境安装SSL安全证书且部署HTTPS网站URL过程)。在这篇文章中老左就不详细演示Let's Encrypt证书证书的安装,后面再重新折腾一篇文章详细的部署证书的安装Nginx和Apache。

ssl_certificate /etc/letsencrypt/live/laozuo.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/laozuo.org/privkey.pem;

比如我们在Nginx环境中,只要将对应的ssl_certificate和ssl_certificate_key路径设置成我们生成的2个文件就可以,最好不要移动和复制文件,因为续期的时候直接续期生成的目录文件就可以,不需要再手工复制。

第四、解决Let's Encrypt免费SSL证书有效期问题

我们从生成的文件中可以看到,Let's Encrypt证书是有效期90天的,需要我们自己手工更新续期才可以。

./letsencrypt-auto certonly --renew-by-default --email admin@laozuo.org -d laozuo.org -d www.laozuo.org

这样我们在90天内再去执行一次就可以解决续期问题,这样又可以继续使用90天。如果我们怕忘记的话也可以制作成定时执行任务,比如每个月执行一次。

第五、关于Let's Encrypt免费SSL证书总结

通过以上几个步骤的学习和应用,我们肯定学会了利用Let's Encrypt免费生成和获取SSL证书文件,随着Let's Encrypt的应用普及,SSL以后直接免费不需要购买,因为大部分主流浏览器都支持且有更多的主流商家的支持和赞助,HTTPS以后看来也是趋势。在Let's Encrypt执行过程在中我们需要解决几个问题。

A - 域名DNS和解析问题。在配置Let's Encrypt免费SSL证书的时候域名一定要解析到当前VPS服务器,而且DNS必须用到海外域名DNS,如果用国内免费DNS可能会导致获取不到错误。

B - 安装Let's Encrypt部署之前需要服务器支持PYTHON2.7以及GIT环境,要不无法部署。

C - Let's Encrypt默认是90天免费,需要手工或者自动续期才可以继续使用。

本文固定链接: http://www.laozuo.org/7676.html | 老左博客

nginx可以根据客户端IP进行负载均衡,在upstream里设置ip_hash,就可以针对同一个C类地址段中的客户端选择同一个后端服务器,除非那个后端服务器宕了才会换一个。

nginx的upstream目前支持的5种方式的分配
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
upstream backserver {
server 192.168.0.14;
server 192.168.0.15;
}

2、指定权重
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
upstream backserver {
server 192.168.0.14 weight=10;
server 192.168.0.15 weight=10;
}

3、IP绑定 ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
upstream backserver {
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
}

4、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream backserver {
server server1;
server server2;
fair;
}

5、url_hash(第三方)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。
upstream backserver {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}

在需要使用负载均衡的server中增加

proxy_pass http://backserver/;
upstream backserver{
ip_hash;
server 127.0.0.1:9090 down; (down 表示单前的server暂时不参与负载)
server 127.0.0.1:8080 weight=2; (weight 默认为1.weight越大,负载的权重就越大)
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup; (其它所有的非backup机器down或者忙的时候,请求backup机器)
}

max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误

fail_timeout:max_fails次失败后,暂停的时间

 

Vultr是一家提供日本、美国、欧洲等多个国家和地区机房的VPS主机商,硬盘都是采用SSD,VPS主机都是KVM架构,VPS配置最少的内存768MB、硬盘为15GB的VPS只要5美元/月,vultr是根据时长来扣费的,使用多长时间就算多长时间,扣对应的款。

Vultr VPS新注册用户赠送50美元优惠活动(可免费使用VPS时间为2个月)

Vultr针对新用户的优惠又来了!! 这次直接注册即送50美金使用60天。60天后50美金自动失效! 本次活动需要信用卡或者或者paypal付款!paypal付款需要充值五美元,信用卡付款则会扣除2.5美元预授权费用(只是预授权,之后钱会回到你的信用卡的)。 2016年1月开始,vultr再次升级月流量,最低配置从原先的400GB增加到目前的1000GB,可以说非常超值,另外vultr 打算2016年一季度在亚洲扩充一个机房数据中心,目前选择是中国香港,韩国首尔,新加坡中的一个,所以,为了避免linode机房那种新用户限制选择东京机房的政策,如果未来有打算使用vultr上面机房数据中心的,建议现在就先注册好账号。

2016.4.7更新 vultr优惠码:NGINX20    新注册用户免费赠送20刀,有效期1年时间!

此外,Vultr VPS除了赠送50美元两个月的计划外,其他的计划都在打8折!无需输入优惠码! (vultr 是禁止用户重复注册账号的,即如果你的支付信息有2个账号在使用,那么你的账户会被关闭)

下面给出具体教程(2016.3.2vultr官网更新,本教程也相应更新):

点击这里查看官网:地址直达

3201

活动地址:http://www.vultr.com/freetrial/

注意:这个是一个新注册用户的优惠活动,所以需要新的账户。点击Sign Up and get $50 for free

3202

vultr 是禁止用户重复注册账号的,即如果你的支付信息有2个账号在使用,那么你的账户会被后台关闭的。简单的说就是一个账户的支付信息比如paypal 账号是对应唯一的一个的,如果你再次使用这个paypal支付另外一个新注册的账号的话,那么账户就会被关闭。所以,重复的注册账号是不可取的。

特别提醒

有部分朋友出现购买vultr的VPS在使用几天甚至付款验证后账户就被关闭,主要原因vultr 是禁止用户重复注册账号的,即如果你使用的paypal或者信用卡已经绑定了Vultr其他账号,那么你新注册的账户会被后台关闭的。简单的说就是一个账户的支付信息比如paypal 账号是对应唯一的一个的,如果你再次使用这个paypal支付另外一个新注册的账号的话,那么账户就会被关闭。所以,重复的注册账号是不可取的。

一 选择信用卡支付

填写信用卡信息,这个预扣款$2.5美元,后面会返还。另外使用优惠码 :NGINX20 可以获得vultr赠送的20美元一年使用权。

3203

这里一个很好的建议是你充值$10美元,防止你被误判恶意使用,如果你使用优惠码NGINX20 ,会被人工审核。这样你就可以免费使用VPS期限7个月了。

二 Paypal支付Vultr (仅限paypal 支付查看,信用卡支付的请忽略)

如果说你没有信用卡,但是你有Paypal 账号,那么你需要先点击上面的Expires 60Days From Today 后面的Remove按钮(谨慎操作,Vultr只给一次机会,选择信用卡的同学切勿选择,本操作仅限paypal支付同学使用 ),输入优惠码 NGINX20 获得20美元一年的使用权。

4701

三 服务器创建

账单信息确认完成,我们就可以点击右侧的3206 Deploy New Server  建立VPS了。

硬盘默认

服务器选择日本 东京(目前日本线路比较绕,选择洛杉矶比较好)

操作系统默认

服务器配置:默认即可。

其他信息默认即可。

点击 place order ,生成一个新VPS。

3207 3208 3209

进入 Servers ,稍等片刻服务器信息就生成了。

3212

点击 Cloud Instance 进行管理。

3211

Vultr 的这个控制面板还是比较清新的,VPS的所有功能都在一个页面集中,服务器停止,重新启动,重装系统,删除服务器等指示清晰,非常容易管理。

3210

按照上面的配置信息我们登录putty,注意vultr 端口号是22. 初次登录密码就是Initial Password 里面的信息,登录后就是我们常规的操作了。

简单简介下putty的使用

首先按照vultr 给我们的信息填写,IP选择控制面板的IP,端口22,选择SSH模式

461

点击open,会有一个窗口,选择是。

462

login as填写 root.密码填写vultr提供的密码。

putty的密码输入进去是不显示的,所以这里的正确操作步骤是:先复制vultr给的密码,注意复制的密码前后不能有空格(如上图正确密码cteyjukrieh!5),然后先鼠标左键点击下putty软件,再在绿色光标那里鼠标右键一下,然后回车键(Enter建)。这里最关键,好多朋友密码总是输入不对,要么是密码复制错误多了空格,要么就是因为没有看到密码显示就多鼠标右键,多复制了几次密码。正确复制密码回车后的界面是这个样子。

464

 vultr相关性能测试

如果你对速度还不爽,还可以做下优化,比如改进下TCP算法:hybla。 或者安装锐速.

TCP算法代码:

加载tcp_hybla模块(OpenVZ在这一步就会报错):

/sbin/modprobe tcp_hybla

然后查看是否已经正常加载:

lsmod |grep hybla

如果你的内核版本较新,比如CentOS 6.x的2.6.32,则可以用下列命令查看当前可用的拥堵算法,里面应该有hybla了:

sysctl net.ipv4.tcp_available_congestion_control

sysctl net.ipv4.tcp_congestion_control=hybla

编辑

vi /etc/sysctl.conf

在文档末行增加

net.ipv4.tcp_congestion_control= hybla

保存加载:

sysctl -p

然后重启即可。

其他可以参考:

我们用这个日本东京VPS来看视频,浏览网页的话是非常给力的。

在本站内购买vultr,加QQ:2102629796,获得免费搭建ss。

锐速给我们tcp连接加速

安装锐速

wget -N --no-check-certificate https://raw.githubusercontent.com/91yun/serverspeeder/master/serverspeeder-all.sh && bash serverspeeder-all.sh

卸载锐速

chattr -i /serverspeeder/etc/apx* && /serverspeeder/bin/serverSpeeder.sh uninstall -f

根据屏幕提示输入 serverSpeederInstaller 其他信息默认,遇到Y或者N的地方,全部选Y.

然后我们按照图片的数据指示,一路回车就可以了。

11707

现在打开你的浏览器试试速度吧,有图为证

vultr

如果你安装没有效果,编辑一下命令

vi /serverspeeder/etc/config

然后rsc和maxmode设置参数修改为1.然后在进行重启

/serverspeeder/bin/serverSpeeder.sh restart

常用命令

启动锐速:

/serverspeeder/bin/serverSpeeder.sh start

停止锐速:

/serverspeeder/bin/serverSpeeder.sh stop

查看锐速是否正常运行

service serverSpeeder status

检查是否有appex0模块:lsmod

lsmod

32

优化博客网页内容时,将js和css指定到static.151051.cn域名下,没想到其中css使用的字体文件无法加载,提示错误信息如下:

Font from origin 'http://static.151051.cn' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.151051.cn' is therefore not allowed access.

好吧,字面上的意思是,字体被禁止调用,原因头信息中并不包含Access-Control-Allow-Origin,没有授权给www.151051.cn使用,原谅我蹩脚的英文。随手百度了一下Access-Control-Allow-Origin这货,原来这货是用来定义允许哪个域使用资源,可以有效解决字体远程调用的问题。一不做二不休,开搞。

如果是php文件,可以在php文件中定义<?php header("Access-Control-Allow-Origin: http://www.151051.cn");?> 注意,这里网上有很多文章是用*代替域名,这样做比较"呵呵",所以还是指定域名比较好,安全性高一些。

像我现在这种需求,在static.151051.cn授权给www.151051.cn使用,而且static并不想支持php,那肿么办呢?

呵呵,好办,直接在nginx里加入到头信息中,一劳永逸。如下:
location ~ .*\.(js|css|woff|ttf|svg|eot|oft)?$
{
add_header Access-Control-Allow-Origin http://www.151051.cn;
expires 2h;
}

好了,解决!

http://www.webkaka.com/blog/archives/how-to-set-gzip-for-js-in-Nginx.html

Nginx启用gzip很简单,只需要设置一下配置文件即可完成,可以参考文章nginx" target="_blank">Nginx如何配置Gzip压缩功能。不过,在群里常有人提到,他们的网站Gzip压缩虽然成功了,但检测到JS仍然没有压缩成功,这是为什么呢?经过我的检查发现,原来是他们的gzip_types设置不对造成的,本文就为遇到同样情况的人解决这一问题。

Nginx启用Gzip压缩js无效

某群友在群里提到,他启用了网站的Gzip压缩,通过站长工具Gzip压缩检测检测到启用成功了,想着其他文件如CSS、JS等也都压缩成功了,但是通过进一步检测各种类型的压缩情况,发现JS文件并没有启用Gzip压缩,这令他非常纳闷,不知何故。

Nginx启用Gzip压缩js无效

图1:Nginx启用Gzip压缩js无效

转自:http://haibo600.blog.51cto.com/blog/1951311/874603

1.worker_processes 越大越好(一定数量后性能增加不明显)
2.worker_cpu_affinity 所有cpu平分worker_processes 要比每个worker_processes 都跨cpu分配性能要好;不考虑php的执行,测试结果worker_processes数量是cpu核数的2倍性能最优
3.unix domain socket(共享内存的方式)要比tcp网络端口配置性能要好
不考虑backlog,请求速度有量级的飞跃,但错误率超过50%
加上backlog,性能有10%左右提升
4.调整nginx、php-fpm和内核的backlog(积压),connect() to unix:/tmp/php-fpm.socket failed (11: Resource temporarily unavailable) while connecting to upstream错误的返回会减少
nginx
配置文件的server块
listen 80 default backlog=1024;
php-fpm:
配置文件的
listen.backlog = 2048
kernel参数:
/etc/sysctl.conf,不能低于上面的配置
net.ipv4.tcp_max_syn_backlog = 4096
net.core.netdev_max_backlog = 4096
5.增加单台服务器上的php-fpm的master实例,会增加fpm的处理能力,也能减少报错返回的几率
多实例启动方法,使用多个配置文件:
/usr/local/php/sbin/php-fpm -y /usr/local/php/etc/php-fpm.conf &
/usr/local/php/sbin/php-fpm -y /usr/local/php/etc/php-fpm1.conf &
nginx的fastcgi配置
    upstream phpbackend {
#      server   127.0.0.1:9000 weight=100 max_fails=10 fail_timeout=30;
#      server   127.0.0.1:9001 weight=100 max_fails=10 fail_timeout=30;
#      server   127.0.0.1:9002 weight=100 max_fails=10 fail_timeout=30;
#      server   127.0.0.1:9003 weight=100 max_fails=10 fail_timeout=30;
      server   unix:/var/www/php-fpm.sock weight=100 max_fails=10 fail_timeout=30;
      server   unix:/var/www/php-fpm1.sock weight=100 max_fails=10 fail_timeout=30;
      server   unix:/var/www/php-fpm2.sock weight=100 max_fails=10 fail_timeout=30;
      server   unix:/var/www/php-fpm3.sock weight=100 max_fails=10 fail_timeout=30;
#      server   unix:/var/www/php-fpm4.sock weight=100 max_fails=10 fail_timeout=30;
#      server   unix:/var/www/php-fpm5.sock weight=100 max_fails=10 fail_timeout=30;
#      server   unix:/var/www/php-fpm6.sock weight=100 max_fails=10 fail_timeout=30;
#      server   unix:/var/www/php-fpm7.sock weight=100 max_fails=10 fail_timeout=30;
    }
        location ~ \.php* {
            fastcgi_pass   phpbackend;
#           fastcgi_pass   unix:/var/www/php-fpm.sock;
            fastcgi_index index.php;
       ..........
       }
6.测试环境和结果
内存2G
swap2G
cpu 2核 Intel(R) Xeon(R) CPU E5405  @ 2.00GHz
采用ab远程访问测试,测试程序为php的字符串处理程序
1)在开4个php-fpm实例,nginx 8个worker_processes 每个cpu4个worker_processes ,backlog为1024,php的backlog为2048,内核backlog为4096,采用unix domain socket连接的情况下,其他保持参数不变
性能和错误率较为平衡,可接受,超过4个fpm实例,性能开始下降,错误率并没有明显下降
结论是fpm实例数,worker_processes数和cpu保持倍数关系,性能较高
影响性能和报错的参数为
php-fpm实例,nginx worker_processes数量,fpm的max_request,php的backlog,unix domain socket
10W请求,500并发无报错,1000并发报错率为0.9%
500并发:
Time taken for tests:   25 seconds avg.
Complete requests:      100000
Failed requests:        0
Write errors:           0
Requests per second:    4000 [#/sec] (mean) avg.
Time per request:       122.313 [ms] (mean)
Time per request:       0.245 [ms] (mean, across all concurrent requests)
Transfer rate:          800 [Kbytes/sec] received avg.
1000并发:
Time taken for tests:   25 seconds avg.
Complete requests:      100000
Failed requests:        524
   (Connect: 0, Length: 524, Exceptions: 0)
Write errors:           0
Non-2xx responses:      524
Requests per second:    3903.25 [#/sec] (mean)
Time per request:       256.197 [ms] (mean)
Time per request:       0.256 [ms] (mean, across all concurrent requests)
Transfer rate:          772.37 [Kbytes/sec] received
2)在其他参数不变,unix domain socket换为tcp网络端口连接,结果如下
500并发:
Concurrency Level:      500
Time taken for tests:   26.934431 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Requests per second:    3712.72 [#/sec] (mean)
Time per request:       134.672 [ms] (mean)
Time per request:       0.269 [ms] (mean, across all concurrent requests)
Transfer rate:          732.37 [Kbytes/sec] received
1000并发:
Concurrency Level:      1000
Time taken for tests:   28.385349 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Requests per second:    3522.94 [#/sec] (mean)
Time per request:       283.853 [ms] (mean)
Time per request:       0.284 [ms] (mean, across all concurrent requests)
Transfer rate:          694.94 [Kbytes/sec] received
与1)比较,有大约10%的性能下降
7. 5.16调整fpm的max_request参数为1000,并发1000报错返回降到200个以下,
Transfer rate在800左右
yum -y install wget --noplugins
wget freevps.us/downloads/nginx-centos-6.sh -O - | bash

注意安装完成后 php-fpm 默认跑在 apache 用户上。

安装完成后,如果你需要的 PHP 扩展未安装,可输入如下命令查询:

yum list | grep ^php*

找到了扩展的名字,就可以直接安装了:

# 以 php memcache 扩展为例
yum install -y php-pecl-memcached

此外还遇到的问题是 DOMDocument 找不到,直接 yum 安装 php-xml:

yum install -y php-xml

所有扩展 yum 安装完成后都需要重新启动 / 载入 php-fpm。
贴下内容来看看(非最新版本,请直接下载 .sh 文件):

#!/bin/bash

##################
# disable apache #
##################
service httpd stop 
chkconfig httpd off
service xinetd stop
chkconfig xinetd off
service saslauthd stop
chkconfig saslauthd off
service sendmail stop
chkconfig sendmail off
service postfix stop
chkconfig postfix off

#Optimize yum on OpenVZ
if [ -e "/proc/user_beancounters" ]
then
  sed -i 's/plugins=1/plugins=0/' /etc/yum.conf
fi

#remove all current PHP and MySQL, will reinstall later. Also, remove apache 
yum -y remove httpd php mysql rsyslog sendmail postfix

###################
# Add a few repos #
###################
# install the Atomic repo for php and nginx (may use epel for nginx depending on version)
wget -q -O - http://www.atomicorp.com/installers/atomic | sh

# RPMForge for nginx dependencies
rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm

#EPEL for syslog-ng and nginx (may use atomic for nginx depending on version)
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm

################################
# Install PHP, NGINX and MySQL #
################################
#yum install GeoIP libGeoIP.so.1 --enablerepo=repoforge
yum -y install mysql-server php-fpm php-mysql php-gd nginx nano exim syslog-ng

#################
# install MySQL #
#################
#yum -y install mysql-server
cat > /etc/my.cnf <<END
[mysqld]
default-storage-engine = myisam
key_buffer = 8M
query_cache_size = 8M
query_cache_limit = 4M
max_connections=25
thread_cache=1
skip-innodb 
query_cache_min_res_unit=0
tmp_table_size = 4M
max_heap_table_size = 4M
table_cache=256
concurrent_insert=2 
END
echo  Do not worry if you see a error stopping MySQL or NGINX
/etc/init.d/mysqld stop
/etc/init.d/mysqld start

####################
# Set up NGINX PHP #
####################
cat > /etc/nginx/php <<END
index index.php index.html index.htm;

location ~ \.php$ {

   include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
  try_files \$uri =404;
    fastcgi_pass 127.0.0.1:9000;
    error_page 404 /404page.html; #makes nginx return it's default 404 
#	page instead of a blank page

} 
END

cat > /etc/nginx/nginx.conf <<END
user              nginx nginx;
worker_processes  2;

error_log         logs/error.log;

pid               logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    client_max_body_size 64M;
    sendfile        on;
    tcp_nopush      on;

    keepalive_timeout  3;

    gzip  on;
    gzip_comp_level 2;
    gzip_proxied any;
    gzip_types      text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    server_tokens off;

    include /etc/nginx/conf.d/*;
} 
END
rm /etc/nginx/conf.d/*
cat > /etc/nginx/conf.d/default.conf <<END
server {
    listen 80 default;
    server_name _;
    root /var/www/html;
    include php;

  } 
END
mkdir /usr/share/nginx/logs/
service nginx restart
chkconfig nginx on
chkconfig mysqld on

cat > /etc/php-fpm.d/www.conf <<END
; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0666
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0666

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives:
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes to be created when pm is set to 'dynamic'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either 'static' or 'dynamic'
; Note: This value is mandatory.
pm.max_children = 5

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 1

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. By default, the status page shows the following
; information:
;   accepted conn    - the number of request accepted by the pool;
;   pool             - the name of the pool;
;   process manager  - static or dynamic;
;   idle processes   - the number of idle processes;
;   active processes - the number of active processes;
;   total processes  - the number of idle + active processes.
; The values of 'idle processes', 'active processes' and 'total processes' are
; updated each second. The value of 'accepted conn' is updated in real time.
; Example output:
;   accepted conn:   12073
;   pool:             www
;   process manager:  static
;   idle processes:   35
;   active processes: 65
;   total processes:  100
; By default the status page output is formatted as text/plain. Passing either
; 'html' or 'json' as a query string will return the corresponding output
; syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set 
;pm.status_path = /status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The log file for slow requests
; Default Value: /var/log/php-fpm.log.slow
;slowlog = /var/log/php-fpm.log.slow

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 

; Chdir to this directory at the start. This value must be an absolute path.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Default Value: no
;catch_workers_output = yes

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 32M
php_admin_value[upload_max_filesize] = 32M
END

mkdir /var/www
mkdir /var/www/html/
useradd apache
service php-fpm start
chkconfig php-fpm on
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
service iptables save

wget freevps.us/downloads/setup-vhost.sh -O /bin/setup-vhost
chmod 755 /bin/setup-vhost
echo "alias nano='nano -w'" >> ~/.bashrc
clear
echo Installation done.
echo to create a vhost, run
echo setup-vhost example.com
echo do not include the www. subdomain.

转:http://www.cnblogs.com/vicowong/archive/2011/12/01/2116212.html

一、CentOS 6安装

1.1 使用VMware 虚拟机进行安装,进行安装界面

(分配内存必须大于1G,否则不会显示图型安装界面,网络设置使用“桥接模式” 即"Bridged"模式)

1.2 选择 Install or upgrade an existing system

1.3 在"Disc found" 框 选择 "skip"

1.4 next 选择 "chinese(simplified)(中文(简介 )) next

1.5 选择 "美国英语式" 下一步

1.6 选择 "基本 存储设备" 下一步

1.7 弹出"警告"框时,选择"重新初始化所有"

1.8 主机名可以保留默认,点击”配置网络“ 弹出“网络连接” 双击“System eth0"

1.9 弹出“正在编辑 System eth0" 选择"自动连接" 点击"应用“ ,点击”关闭“ 关闭”网络连接“框 下一步

1.10 不要选择“系统时钟使用UTC时间” 下一步

1.11 输入并确认 ”根密码“ 下一步

1.12 选择"替换现有Linux系统 " 下一步 “将修改写入磁盘"

1.13 选择"Basic Server" 下一步

1.14 大概一共590个软件包,复制安装完成后,点击“重新引导”,重新启动计算机

1.15 (安装完成后,可以将虚拟机内存由1G,改为512M)

 

二、更新centos6

2.1 更新

yum update -y

2.2 查看版本,确认为"CentOS Linux release 6.0 (Final)"

lsb_release -a

2.2 安装编译器

yum install -y gcc gcc-c++

 

三、安装Google-perftools (使用tcmalloc 加速 mysql 和 nginx)

3.1下载需要的文件

下载 libunwind-1.0.1.tar.gz 到 /usr/local/data-original

3.2 安装libunwind

cd /usr/local/data-original/

tar zvxf libunwind-1.0.1.tar.gz

cd libunwind-1.0.1

./configure --enable-shared

make && make install

3.3 安装google-perftools

cd /usr/local/data-original/

tar zvxf google-perftools-1.8.3.tar.gz

cd google-perftools-1.8.3

./configure --enable-shared --enable-frame-pointers

make && make install

3.4 更新,使动态链接库能够被系统共享

echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf

ldconfig

 

四、安装mysql

4.1.下载文件

下载 ncurses-5.9.tar.gz到/usr/local/data-original
下载 bison-2.5.tar.gz到/usr/local/data-original
下载 cmake-2.8.6.tar.gz到/usr/local/data-original
下载 mysql-5.5.18.tar.gz到/usr/local/data-original

4.2 安装ncurses

yum install ncurses-devel -y

cd /usr/local/data-original/

tar zvxf ncurses-5.9

./configure

make && make install

4.3 安装cmake

cd /usr/local/data-original/

tar zvxf cmake-2.8.6.tar.gz

cd cmake-2.8.6

./bootstrap

make && make install

4.4 安装bison

cd /usr/local/data-original/

tar zvxf bison-2.5.tar.gz

cd bison-2.5

./configure

make && make install

4.5 创建mysql需要的目录、配置用户和用户组

groupadd mysql

useradd -g mysql mysql

mkdir -p /data/mysql

chown -R mysql:mysql /data/mysql

4.6.安装mysql (需要 cmake ncurses-devel bison 库)

4.6.1 安装

cd /usr/local/data-original/

tar zvxf mysql-5.5.18.tar.gz

cd mysql-5.5.18

cmake -DCMAKE_INSTALL_PREFIX=/opt/mysql -DMYSQL_DATADIR=/data/mysql -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_MYISAM_STORAGE_ENGINE=1 -DSYSCONFDIR=/etc/ -DWITH_SSL=yes -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH_READLINE=on

make && make install

4.6.2 创建软连接

ln -s /opt/mysql/lib/lib* /usr/lib/

4.6.3 配置mysql数据库

cd /opt/mysql
./scripts/mysql_install_db --basedir=/opt/mysql/ --datadir=/data/mysql/ --user=mysql

4.6.4 复制配置文件

cp ./support-files/my-large.cnf /etc/my.cnf

4.6.5 修改配置文件,设置默认使用utf8编码

vim /etc/my.cnf
在[client]下添加一行
default-character-set = utf8
在[mysqld]下添加一行
character-set-server = utf8

4.6.6 设置mysql开机自动启动服务
cp ./support-files/mysql.server /etc/rc.d/init.d/mysqld
chkconfig --add mysqld
chkconfig --level 345 mysqld on

4.6.7 修改服务配置文件
vim /etc/rc.d/init.d/mysqld

根据设定需要,修改mysqld文件中的下面两项
basedir=/opt/mysql
datadir=/data/mysql

4.6.8 启动mysqld服务
service mysqld start

4.6.9 数据库初始化及修改root密码(root初始密码为空)
./bin/mysql_secure_installation
根据提示操作

4.6.10 软连接mysql

ln -s /opt/mysql/bin/mysql /bin

4.6.11 重启centos后,尝试用root连接mysql
mysql -u root -p

成功登录后查看状态

status;

4.6.12 使用tcmalloc优化mysql ( 需要安装google-perftools)

修改MySQL启动脚本(根据你的MySQL安装位置而定)
vim /opt/mysql/bin/mysqld_safe

在# executing mysqld_safe的下一行,加上:
export LD_PRELOAD=/usr/local/lib/libtcmalloc.so

4.6.13 重启服务,查看tcmalloc是否生效 (第二条命令显示即生效)

service mysqld restart

lsof -n | grep tcmalloc

如果显示以下类似的信息,即表示tcmalloc生效

[root@localhost mysql]# lsof -n|grep tcmalloc
mysqld 30347 mysql mem REG 253,0 2177570 544322 /usr/local/lib/libtcmalloc.so.0.2.2

 

五、安装Nginx

5.1.准备安装

下载 pcre-8.20.tar.gz到/usr/local/data-original

下载 nginx-1.0.10.tar.gz到/usr/local/data-original

5.2 更新包

yum install zlib* openssl* -y

 

5.3 安装Pcre

cd /usr/local/data-original/

tar zvxf pcre-8.20.tar.gz

cd pcre-8.20

./configure

make && make install

5.4 创建www用户和组,创建www虚拟主机使用的目录,以及Nginx使用的日志目录,并且赋予他们适当的权限

groupadd www
useradd -g www www

mkdir -p /data/www
chmod +w /data/www
chown -R www:www /data/www

为tcmalloc添加目录,并且赋予适当权限

mkdir -p /tmp/tcmalloc/

chown -R www:www /tmp/tcmalloc/

 

5.1 安装Nginx (需要 pcre google-perftools 库)

5.5.1 安装

cd /usr/local/data-original/

tar zvxf nginx-1.0.10.tar.gz

伪装服务器信息(可以不修改)

cd nginx-1.0.10/data-original/core

vim ./data-original/core/nginx.h

修改NGINX_VERSION为你希望显示的版号

修改NGINX_VER为你希望显示的名称

修改NGINX_VAR 为你希望显示的名称

保存

开始安装

./configure --user=www --group=www --prefix=/opt/nginx --with-http_stub_status_module --with-http_ssl_module --with-google_perftools_module

make && make install

5.4.2 修改 nginx.conf ,令nginx可以 google-perftools实现加速

vim /opt/nginx/conf/nginx.conf

修改前面几行为:

user www www;
worker_processes 8;
error_log logs/error.log crit;
pid logs/nginx.pid;
google_perftools_profiles /tmp/tcmalloc/;
events{
use epoll;
worker_connections 65535;
}

 

5.4.3 测试和运行

cd /opt/nginx

./sbin/nginx -t

如果显示下面信息,即表示配置没问题

nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

输入代码运行nginx服务

./sbin/nginx

ps au|grep nginx

如果显以类似下面的信息,即表示nginx已经启动

root 2013 0.0 0.0 103156 856 pts/0 S+ 03:22 0:00 grep nginx

输入代码检测是否支持加速

lsof -n | grep tcmalloc

如果显示类似下面的信息,即表示支持tcmalloc加速 (mysqld和nginx两个线程都支持)

mysqld 20818 mysql mem REG 253,0 2177570 281050 /usr/local/lib/libtcmalloc.so.0.2.2

nginx 29454 www 25w REG 253,0 0 288399 /tmp/tcmalloc/.29454

nginx 29455 www 27w REG 253,0 0 288403 /tmp/tcmalloc/.29455

 

5.5.4 打开防火墙80端口

写入规则,保存并重启服务

iptables -I INPUT -p tcp --dport 80 -j ACCEPT

/etc/rc.d/init.d/iptables save

/etc/init.d/iptables restart

查看防火墙信息
/etc/init.d/iptables status

如果显示以下类似信息,即表示已经打开了80端口

1 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80

5.5.5 编写nginx 启动服务

cd /etc/init.d

vim nginx

输入以下代码并保存

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/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="/opt/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}

stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
killall -9 nginx
}

restart() {
configtest || return $?
stop
sleep 1
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

chkconfig --level 345 nginx on

service nginx start



六、安装PHP

6.1 准备安装

下载php-5.3.6.tar.gz到/usr/local/data-original
下载 libiconv-1.14.tar.gz到/usr/local/data-original
下载 libmcrypt-2.5.8.tar.gz到/usr/local/data-original
下载mcrypt-2.6.8.tar.gz到/usr/local/data-original
下载mhash-0.9.9.9.tar.gz到/usr/local/data-original
下载libmcrypt-2.5.8.tar.gz到/usr/local/data-original

yum -y install autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers libXpm* gcc gcc-c++

 

5.2 安装libiconv (加强系统对支持字符编码转换的功能)

cd /usr/local/data-original/

tar zvxf libiconv-1.14.tar.gz

cd libiconv-1.14

./configure --prefix=/usr/local

make && make install

5.3 安装libmcrypt(加密算法库,PHP扩展mcrypt功能对此库有依耐关系,要使用mcrypt必须先安装此库)

5.3.1 安装libmcrypt

cd /usr/local/data-original/

tar zvxf libmcrypt-2.5.8.tar.gz

cd libmcrypt-2.5.8

./configure

make && make install

5.3.2安装libltdl

cd libltdl/

./configure --enable-ltdl-install

make && make install

5.3.3 更新共享

ln -sf /usr/local/lib/libmcrypt.* /usr/lib64/
ln -sf /usr/local/bin/libmcrypt-config /usr/lib64/
#ln -sf /usr/local/lib/libiconv.so.2 /usr/lib64/

ldconfig

5.4 安装mhash(hash加密算法库)

5.4.1 安装mhash

cd /usr/local/data-original/

tar zvxf mhash-0.9.9.9.tar.gz

cd mhash-0.9.9.9

./configure

make && make install

5.4.2更新共享

ln -sf /usr/local/lib/libmhash.* /usr/lib64/

ldconfig

5.5 安装mcrypt

cd /usr/local/data-original/

tar zvxf mcrypt-2.6.8.tar.gz

cd mcrypt-2.6.8

ldconfig

./configure

make && make install

5.6 安装php

5.6.1 创建mysql软连接、ldap软连接

mkdir -p /opt/mysql/include/mysql
ln -s /opt/mysql/include/* /opt/mysql/include/mysql/

ln -s /usr/lib64/libldap* /usr/lib

5.6.2 安装

cd /usr/local/data-original/

tar zvxf php-5.3.8.tar.gz

cd php-5.3.8

./configure --prefix=/opt/php --with-config-file-path=/opt/php/etc --with-mysql=/opt/mysql --with-mysqli=/opt/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --disable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap

make ZEND_EXTRA_LIBS='-liconv'

make install

5.6.3 复制配置文件

cp php.ini-production /opt/php/etc/php.ini

5.6.4 安装memcache扩展(已经安装PHP)

cd /usr/local/data-original/

tar zvxf memcache-2.2.6.tar.gz

cd memcache-2.2.6

/opt/php/bin/phpize

ldconfig

./configure --with-php-config=/opt/php/bin/php-config

make && make install

修改php配置文件,支持memcache

vim /opt/php/etc/php.ini

在文件中搜索extension_dir、extension ,在相应位置添加下面两行
extension_dir = "/opt/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension = "memcache.so"

5.6.5 安装eaccelerator扩展(已经安装PHP)

cd /usr/local/data-original/

tar jxvf eaccelerator-0.9.6.1.tar.bz2

cd eaccelerator-0.9.6.1

/opt/php/bin/phpize

./configure --enable-eaccelerator=shared --with-php-config=/opt/php/bin/php-config

make && make install

修改php配置文件,支持eaccelerator

vim /opt/php/etc/php.ini

在文件尾加入以下代码

[eaccelerator]
zend_extension="/opt/php/lib/php/extensions/no-debug-non-zts-20090626/eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.log_file = "/opt/php/var/log/eaccelerator_log"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="3600"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

增加eaccelerator目录
mkdir -p /tmp/eaccelerator
5.6.5 安装php-fpm

cp /opt/php/etc/php-fpm.conf.default /opt/php/etc/php-fpm.conf
vim /opt/php/etc/php-fpm.conf

修改以下地方
[global]
pid = run/php-fpm.pid-p
error_log = log/php-fpm.log
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 5s
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35

[www]
user = www
group = www

5.6.6 修改nginx,支持php

vim /opt/nginx/conf/nginx.conf

找到并修改以下代码

location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
include fastcgi_params;
}

 

5.6.7将php-fpm 作为服务运行

cd /usr/local/data-original/php-5.3.8
cp ./sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod 700 /etc/init.d/php-fpm
chkconfig --add php-fpm
chkconfig --level 345 php-fpm on
服务方式启动php-fpm
service php-fpm restart

 

5.6.8 编写测试页面

vim /data/www/index.php

输入代码

<html>
<head><title>hello php</title></head>
<body>
<?php phpinfo();?>
</body>
</html>

5.6.8 打开浏览器进行测试

转:http://blog.csdn.net/xymyeah/article/details/6939544

一、一般来说nginx 配置文件中对优化比较有作用的为以下几项:

1. worker_processes 8;

nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计为8)。

2. worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

为每个进程分配cpu,上例中将8 个进程分配到8 个cpu,当然可以写多个,或者将一
个进程分配到多个cpu。

3. worker_rlimit_nofile 65535;

这个指令是指当一个nginx 进程打开的最多文件描述符数目,理论值应该是最多打开文
件数(ulimit -n)与nginx 进程数相除,但是nginx 分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。

现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。

这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。

查看linux系统文件描述符的方法:

[root@web001 ~]# sysctl -a | grep fs.file

fs.file-max = 789972

fs.file-nr = 510 0 789972

4. use epoll;
使用epoll 的I/O 模型

(

补充说明:

与apache相类,nginx针对不同的操作系统,有不同的事件模型

A)标准事件模型
Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll
B)高效事件模型
Kqueue:使用于 FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X. 使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。
Epoll: 使用于Linux内核2.6版本及以后的系统。

/dev/poll:使用于 Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。

Eventport:使用于 Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装安全补丁。

)

5. worker_connections 65535;

每个进程允许的最多连接数, 理论上每台nginx 服务器的最大连接数为worker_processes*worker_connections。

6. keepalive_timeout 60;

keepalive 超时时间。

7. client_header_buffer_size 4k;

客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。

分页大小可以用命令getconf PAGESIZE 取得。

[root@web001 ~]# getconf PAGESIZE

4096

但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。

8. open_file_cache max=65535 inactive=60s;

这个将为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。

9. open_file_cache_valid 80s;

这个是指多长时间检查一次缓存的有效信息。

10. open_file_cache_min_uses 1;

open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。

二、关于内核参数的优化:

net.ipv4.tcp_max_tw_buckets = 6000

timewait 的数量,默认是180000。

net.ipv4.ip_local_port_range = 1024 65000

允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1

启用timewait 快速回收。

net.ipv4.tcp_tw_reuse = 1

开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接。

net.ipv4.tcp_syncookies = 1

开启SYN Cookies,当出现SYN 等待队列溢出时,启用cookies 来处理。

net.core.somaxconn = 262144

web 应用中listen 函数的backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx 定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。

net.core.netdev_max_backlog = 262144

每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans = 262144

系统中最多有多少个TCP 套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS 攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。

net.ipv4.tcp_max_syn_backlog = 262144

记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M 内存的系统而言,缺省值是1024,小内存的系统则是128。

net.ipv4.tcp_timestamps = 0

时间戳可以避免序列号的卷绕。一个1Gbps 的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。

net.ipv4.tcp_synack_retries = 1

为了打开对端的连接,内核需要发送一个SYN 并附带一个回应前面一个SYN 的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK 包的数量。

net.ipv4.tcp_syn_retries = 1

在内核放弃建立连接之前发送SYN 包的数量。

net.ipv4.tcp_fin_timeout = 1

如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2 状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60 秒。2.2 内核的通常值是180 秒,3你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB 服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2 的危险性比FIN-WAIT-1 要小,因为它最多只能吃掉1.5K 内存,但是它们的生存期长些。

net.ipv4.tcp_keepalive_time = 30

当keepalive 起用的时候,TCP 发送keepalive 消息的频度。缺省是2 小时。

三、下面贴一个完整的内核优化设置:

vi /etc/sysctl.conf CentOS5.5中可以将所有内容清空直接替换为如下内容:

net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000

使配置立即生效可使用如下命令:
/sbin/sysctl -p

四、下面是关于系统连接数的优化

linux 默认值 open files 和 max user processes 为 1024

#ulimit -n

1024

#ulimit –u

1024

问题描述: 说明 server 只允许同时打开 1024 个文件,处理 1024 个用户进程

使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n 可以查看当前的最大打开文件数。

新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files 。因此,需要将其改大。

解决方法:

使用 ulimit –n 65535 可即时修改,但重启后就无效了。(注ulimit -SHn 65535 等效 ulimit -n 65535 ,-S 指soft ,-H 指hard)

有如下三种修改方式:

1. 在/etc/rc.local 中增加一行 ulimit -SHn 65535
2. 在/etc/profile 中增加一行 ulimit -SHn 65535
3. 在/etc/security/limits.conf 最后增加:

* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535

具体使用哪种,在 CentOS 中使用第1 种方式无效果,使用第3 种方式有效果,而在Debian 中使用第2 种有效果

# ulimit -n

65535

# ulimit -u

65535

备注:ulimit 命令本身就有分软硬设置,加-H 就是硬,加-S 就是软默认显示的是软限制

soft 限制指的是当前系统生效的设置值。 hard 限制值可以被普通用户降低。但是不能增加。 soft 限制不能设置的比 hard 限制更高。 只有 root 用户才能够增加 hard 限制值。

五、下面是一个简单的nginx 配置文件:

user www www;
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000
01000000;
error_log /www/log/nginx_error.log crit;
pid /usr/local/nginx/nginx.pid;
worker_rlimit_nofile 204800;
events
{
use epoll;
worker_connections 204800;
}
http
{
include mime.types;
default_type application/octet-stream;
charset utf-8;
server_names_hash_bucket_size 128;
client_header_buffer_size 2k;
large_client_header_buffers 4 4k;
client_max_body_size 8m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
keys_zone=TEST:10m
inactive=5m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
fastcgi_busy_buffers_size 8k;
fastcgi_temp_file_write_size 8k;
fastcgi_cache TEST;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
open_file_cache max=204800 inactive=20s;
open_file_cache_min_uses 1;
open_file_cache_valid 30s;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
server
{
listen 8080;
server_name backup.aiju.com;
index index.php index.htm;
root /www/html/;
location /status
{
stub_status on;
}
location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$
{
expires 30d;
}
log_format access ‘$remote_addr — $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” $http_x_forwarded_for’;
access_log /www/log/access.log access;
}
}

六、关于FastCGI 的几个指令:

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10minactive=5m;

这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;

指定连接到后端FastCGI 的超时时间。

fastcgi_send_timeout 300;

向FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI 传送请求的超时时间。

fastcgi_read_timeout 300;

接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI 应答的超时时间。

fastcgi_buffer_size 4k;

指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k。

fastcgi_buffers 8 4k;

指定本地需要用多少和多大的缓冲区来缓冲FastCGI 的应答。

fastcgi_busy_buffers_size 8k;

这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers 的两倍。

fastcgi_temp_file_write_size 8k;

在写入fastcgi_temp_path 时将用多大的数据块,默认值是fastcgi_buffers 的两倍。

fastcgi_cache TEST

开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU 负载,并且防止502 错误。

fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;

为指定的应答代码指定缓存时间,如上例中将200,302 应答缓存一小时,301 应答缓存1 天,其他为1 分钟。

fastcgi_cache_min_uses 1;

缓存在fastcgi_cache_path 指令inactive 参数值时间内的最少使用次数,如上例,如果在5 分钟内某文件1 次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500;

不知道这个参数的作用,猜想应该是让nginx 知道哪些类型的缓存是没用的。以上为nginx 中FastCGI 相关参数,另外,FastCGI 自身也有一些配置需要进行优化,如果你使用php-fpm 来管理FastCGI,可以修改配置文件中的以下值:

60

同时处理的并发请求数,即它将开启最多60 个子线程来处理并发连接。

102400

最多打开文件数。

204800

每个进程在重置之前能够执行的最多请求数。