您的位置:首页 > 编程语言 > PHP开发

配置 php-fpm 监听的socket

2016-01-07 18:38 776 查看
一般现在我们配置的PHP的web环境,如LNMP(linux+Nginx+Mysql+PHP),这里linux可能是centos,ubuntu...,数据库可能是mysql,postgresql,sqlserver等。。

在服务器上安装PHP-FPM,nginx后,我们要配置Nginx的http模块,让.php的文件由nginx转发给PHP-FPM处理,然后在将php-fpm的处理结果通过http响应传给浏览器,就完成了一次http的请求。。

在配置Nginx的http模块的时候,通常是这样:

server~\.php${
includesnippets/fastcgi-php.conf;
fastcgi_pass127.0.0.1:9000;
}

也可以这样,

server~\.php${
includesnippets/fastcgi-php.conf;
fastcgi_passunix:/var/run/php5-fpm.sock;
}


那么这两种方式有什么区别呢??

这就是我这篇博文所要解释的问题。下面,我带大家来分析一下其中的原理,一下是我的一些理解,不对的地方还请大家不吝赐教,我将很感激~~[/code]
PHP-FPMcanlistenonmultiplesockets.IalsolistenonUnixsockets,orTCPsockets.SeehowthisworksandhowtoensureNginxisproperlysendingrequeststoPHP-FPM.

CommandRundown

DefaultConfiguration

EditPHP-FPMconfiguration

#ConfigurePHP-FPMdefaultresourcepool
sudovim/etc/php5/fpm/pool.d/www.conf

PHP-FPMListenconfiguration:

#Stuffomitted
listen=/var/run/php5-fpm.sock
listen.owner=www-data
listen.group=www-data

AlsoeditNginxandseewhereit'ssendingrequesttoPHP-FPM:

#Files:/etc/nginx/sites-available/default

#...stuffomitted

server~\.php${ includesnippets/fastcgi-php.conf; fastcgi_passunix:/var/run/php5-fpm.sock; }

WecanseeabovethatNginxissendingrequeststoPHP-FPMviaaunixsocket(fauxfile)at
/var/run/php5-fpm.sock
.Thisisalsowherethe
www.conf
fileissettingPHP-FPMtolistenforconnections.

UnixSockets

Thesearesecureinthattheyarefile-basedandcan'tbereadbyremoteservers.Wecanfurtheruselinuxpermissiontosetwhocanreadandwritetothissocketfile.

Nginxisrunasuser/group
www-data
.PHP-FPM'sunixsocketthereforeneedstobereadable/writablebythisuser.

IfwechangetheUnixsocketownertouser/group
ubuntu
,Nginxwillthenreturnabadgatewayerror,asitcannolongercommunicatetothesocketfile.WewouldhavetochangeNginxtorunasuser"ubuntu"aswell,orsetthesocketfiletoallow"other"(nonusernorgroup)toberead/writtento,whichisinsecure.

#Stuffomitted
listen=/var/run/php5-fpm.sock
listen.owner=ubuntu
listen.group=ubuntu

So,filepermissionsarethesecuritymechanismforPHP-FPMwhenusingaunixsocket.Thefaux-file'suser/groupandit'suser/group/otherpermissionsdetermineswhatlocalusersandprocessesandreadandwritetothePHP-FPMsocket.

TCPSockets

SettingtheListendirectivetoaTCPsocket(ipaddressandport)makesPHP-FPMlistenoverthenetworkratherthanasaunixsocket.ThismakesPHP-FPMabletobelistenedtobyremoteservers(orstilllocallyoverthelocalhostnetwork).

ChangeListento
Listen127.0.0.1:9000
tomakePHP-FPMlistenonthelocalhostnetwork.Forsecurity,wecanusethe
listen.allowed_clients
ratherthansettheowner/groupofthesocket.

PHP-FPM:

#Listenonlocalhostport9000
Listen127.0.0.1:9000
#EnsureonlylocalhostcanconnecttoPHP-FPM
listen.allowed_clients=127.0.0.1

Nginx:

#Files:/etc/nginx/sites-available/default

#...stuffomitted

server~\.php${ includesnippets/fastcgi-php.conf; fastcgi_pass127.0.0.1:9000; }

http://lists.freebsd.org/pipermail/freebsd-performance/2005-February/001143.html

unixdomainsocketsvs.internetsockets

RobertWatsonrwatsonatFreeBSD.org
FriFeb2502:29:14PST2005


Previousmessage:unixdomainsocketsvs.internetsockets

Nextmessage:unixdomainsocketsvs.internetsockets

Messagessortedby:[date][thread][subject][author]

OnFri,25Feb2005,BarisSimsekwrote:

>Iamcodingadaemonprogram.Iamnotsureaboutwhichtypeofsockets
>ishoulduse.Couldyoucompareipsocketsandunixdomainsockets?My
>maincriterionsareperformanceandprotocolload.Whatarethe
>differencesbetweenimpelementationsofthematkernellevel?

Thereareafewdifferencesthatmightbeofinterest,inadditiontothe
alreadypointedoutdifferencethatifyoustartoutusingIPsockets,you
don'thavetomigratetothemlaterwhenyouwantinter-machine
connectivity:

-UNIXdomainsocketsusethefilesystemastheaddressnamespace.This
meansyoucanuseUNIXfilepermissionstocontrolaccesstocommunicate
withthem.I.e.,youcanlimitwhatotherprocessescanconnecttothe
daemon--maybeoneusercan,butthewebservercan't,orthelike.
WithIPsockets,theabilitytoconnecttoyourdaemonisexposedoff
thecurrentsystem,soadditionalstepsmayhavetobetakenfor
security.Ontheotherhand,yougetnetworktransparency.WithUNIX
domainsockets,youcanactuallyretrievethecredentialoftheprocess
thatcreatedtheremotesocket,andusethatforaccesscontrolalso,
whichcanbequiteconvenientonmulti-usersystems.

-IPsocketsoverlocalhostarebasicallyloopedbacknetworkon-the-wire
IP.Thereisintentionally"nospecialknowledge"ofthefactthatthe
connectionistothesamesystem,sonoeffortismadetobypassthe
normalIPstackmechanismsforperformancereasons.Forexample,
transmissionoverTCPwillalwaysinvolvetwocontextswitchestogetto
theremotesocket,asyouhavetoswitchthroughthenetisr,which
occursfollowingthe"loopback"ofthepacketthroughthesynthetic
loopbackinterface.Likewise,yougetalltheoverheadofACKs,TCP
flowcontrol,encapsulation/decapsulation,etc.Routingwillbe
performedinordertodecideifthepacketsgotothelocalhost.
LargesendswillhavetobebrokendownintoMTU-sizedatagrams,which
alsoaddsoverheadforlargewrites.It'sreallyTCP,itjustgoesover
aloopbackinterfacebyvirtueofaspecialaddress,ordiscoveringthat
theaddressrequestedisservedlocallyratherthanoveranethernet
(etc).

-UNIXdomainsocketshaveexplicitknowledgethatthey'reexecutingon
thesamesystem.Theyavoidtheextracontextswitchthroughthe
netisr,andasendingthreadwillwritethestreamordatagramsdirectly
intothereceivingsocketbuffer.Nochecksumsarecalculated,no
headersareinserted,noroutingisperformed,etc.Becausetheyhave
accesstotheremotesocketbuffer,theycanalsodirectlyprovide
feedbacktothesenderwhenitisfilling,ormoreimportantly,
emptying,ratherthanhavingtheaddedoverheadofexplicit
acknowledgementandwindowchanges.Theonepieceoffunctionalitythat
UNIXdomainsocketsdon'tprovidethatTCPdoesisout-of-banddata.In
practice,thisisanissueforalmostnoone.

Ingeneral,theargumentforimplementingoverTCPisthatitgivesyou
locationindependenceandimmediateportability--youcanmovetheclient
orthedaemon,updateanaddress,anditwill"justwork".Thesockets
layerprovidesareasonableabstractionofcommunicationsservices,so
it'snothardtowriteanapplicationsothattheconnection/binding
portionknowsaboutTCPandUNIXdomainsockets,andalltherestjust
usesthesocketit'sgiven.Soifyou'relookingforperformancelocally,
IthinkUNIXdomainsocketsprobablybestmeetyourneed.Manypeople
willcodetoTCPanywaybecauseperformanceisoftenlesscritical,and
thenetworkportabilitybenefitissubstantial.

Rightnow,theUNIXdomainsocketcodeiscoveredbyasubsystemlock;I
haveaversionthatusedmorefine-grainlocking,buthavenotyet
evaluatedtheperformanceimpactofthosechanges.I'veyou'rerunningin
anSMPenvironmentwithfourprocessors,itcouldbethatthosechanges
mightpositivelyimpactperformance,soifyou'dlikethepatches,letme
know.Rightnowthey'reonmyscheduletostarttesting,butnotonthe
pathforinclusioninFreeBSD5.4.Theprimarybenefitofgreater
granularitywouldbeifyouhadmanypairsofthreads/processes
communicatingacrossprocessorsusingUNIXdomainsockets,andasaresult
therewassubstantialcontentionontheUNIXdomainsocketsubsystemlock.
Thepatchesdon'tincreasethecostofnormalsend/receiveoperations,but
dueaddextramutexoperationsinthelisten/accept/connect/bindpaths.

RobertNMWatson


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: