NginxÐéÄâÖ÷»ú¸ºÔØƽºâÉèÖã¬ÊµÏÖ¶àÓòÃûÊ¿Á¿·Ö·¢
nginxÐéÄâÖ÷»ú¸ºÔØƽºâÉèÖã¬ÊµÏÖ¶àÓòÃûÊ¿Á¿·Ö·¢
СÐò£º
ÔÚÏÖ´úÍøÂçÓ¦ÓóÌÐòÖУ¬¸ºÔØƽºâÊÇÌá¸ßϵͳÎȹÌÐÔºÍÐÔÄܵÄÖ÷ÒªÒòËØ¡£Nginx×÷Ϊһ¿î¸ßÐÔÄܵÄWebЧÀÍÆ÷£¬¿ÉÒÔʹÓÃÆäÇ¿Ê¢µÄ¸ºÔØƽºâ¹¦Ð§À´ÊµÏÖ¶àÓòÃûÊ¿Á¿·Ö·¢¡£±¾ÎĽ«ÏÈÈÝÔõÑùÉèÖÃNginxÐéÄâÖ÷»ú¸ºÔØƽºâ£¬´Ó¶øʵÏÖ¶à¸öÓòÃûµÄÁ÷Á¿·Ö·¢¡£
Ò»¡¢»ù´¡ÇéÐÎ×¼±¸£º
ÔÚ×îÏÈ֮ǰ£¬ÎÒÃÇÐèҪȷ±£ÒѾװÖÃÁËNginx£¬²¢ÇҾ߱¸ÒÔϼ¸¸ö»ù´¡ÒªËØ£º
¶à¸öÓòÃûÖ¸Ïòͳһ¸öЧÀÍÆ÷IP£»
ÿ¸öÓòÃûÒѾÔÚNginxµÄÉèÖÃÎļþÖоÙÐÐÁËÉèÖá£
¶þ¡¢NginxÐéÄâÖ÷»ú¸ºÔØƽºâÉèÖð취£º
½¨ÉèÒ»¸öеÄÉèÖÃÎļþvhost.conf£º
ÔÚNginxµÄÉèÖÃĿ¼Ï£¬Ð½¨Ò»¸öÃûΪvhost.confµÄÎļþ£¬²¢ÔÚ¸ÃÎļþÖÐÌí¼ÓÈçÏÂÄÚÈÝ£º
http { upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÉèÖÃÎļþÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪbackendµÄ¸ºÔØƽºâ¼¯Èº£¬ÆäÖÐbackend1.example.com¡¢backend2.example.com¡¢backend3.example.comÊǺó¶ËЧÀÍÆ÷µÄÓòÃû»òIPµØµã¡£ÔÚserver¿éÖУ¬ÎÒÃÇÖ¸¶¨¼àÌý80¶Ë¿Ú£¬²¢½«ËùÓÐÇëÇóת·¢µ½backend¼¯Èº¡£
ÐÞ¸ÄÖ÷ÉèÖÃÎļþnginx.conf£º
·¿ªNginxµÄÖ÷ÉèÖÃÎļþnginx.conf£¬²¢ÔÚhttp¿éÖеÄincludeÓï¾äÖÐÌí¼ÓÈçÏÂÄÚÈÝ£º
http { ... include /path/to/vhost.conf; ... }
µÇ¼ºó¸´ÖÆ
½«/path/to/vhost.confÌæ»»³ÉÏÖʵµÄvhost.confÎļþ·¾¶¡£
ÖØмÓÔØNginxÉèÖãº
ÉúÑÄvhost.confºÍnginx.confÎļþµÄÐ޸ģ¬²¢ÔËÐÐÒÔÏÂÏÂÁîÖØмÓÔØNginxµÄÉèÖÃÎļþ£º
nginx -s reload
µÇ¼ºó¸´ÖÆ
Èý¡¢²âÊÔÓëÑéÖ¤£º
Íê³ÉÉÏÊöÉèÖúó£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔÏ°취¾ÙÐвâÊÔÓëÑéÖ¤£º
ÐÞ¸ÄÍâµØhostsÎļþ£º
½«example.comµÄÆÊÎöµØµãÐÞ¸ÄΪNginxЧÀÍÆ÷µÄIPµØµã¡£ÔÚWindowsϵͳÖУ¬hostsÎļþλÓÚC:WindowsSystem32driversetchosts£¬ÔÚLinuxϵͳÖУ¬hostsÎļþλÓÚ/etc/hosts¡£
ÔÚä¯ÀÀÆ÷Öлá¼û²âÊÔÓòÃû£º
ÔÚä¯ÀÀÆ÷ÖÐÊäÈëhttp://example.com£¬È»ºó¶à´ÎË¢ÐÂÒ³Ã棬ÊÓ²ìÇëÇóÊÇ·ñÕý³£·Ö·¢¸øºó¶ËЧÀÍÆ÷¡£ÈôÊÇÒ»ÇÐÕý³££¬Ä㽫»á¿´µ½¶à¸öºó¶ËЧÀÍÆ÷½»ÌæÏìÓ¦ÇëÇóµÄÇéÐΡ£
ËÄ¡¢ÆäËû³£ÓÃÉèÖÃÑ¡Ï
³ýÁË»ù±¾µÄ¸ºÔØƽºâÉèÖã¬Nginx»¹ÌṩÁËÐí¶àÆäËûµÄÉèÖÃÑ¡ÏÒÔÖª×ã²î±ðµÄÐèÇó£¬ÒÔÏÂÊÇһЩ³£ÓõÄÉèÖÃÑ¡ÏîʾÀý£º
ȨÖØÉèÖãº
upstream backend { server backend1.example.com weight=3; server backend2.example.com weight=2; server backend3.example.com; }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃÇͨ¹ýweight²ÎÊýÉèÖÃÁ˲î±ðºó¶ËЧÀÍÆ÷µÄȨÖØ£¬È¨ÖØÔ½¸ßµÄЧÀÍÆ÷½«·ÖÅɵ½¸ü¶àµÄÁ÷Á¿¡£
IP¹ÊÕÏתÒÆ£º
upstream backend { ip_hash; server backend1.example.com; server backend2.example.com; server backend3.example.com; }
µÇ¼ºó¸´ÖÆ
ͨ¹ýÉèÖÃip_hash²ÎÊý£¬Nginx½«Æ¾Ö¤ÇëÇóµÄIPµØµã¾ÙÐйÊÕÏתÒÆ£¬¼´ÏàͬIPµÄÇëÇó½«×ÜÊDZ»·Ö·¢µ½Í³Ò»Ì¨ºó¶ËЧÀÍÆ÷¡£
¿µ½¡¼ì²é£º
http { upstream backend { server backend1.example.com max_fails=2 fail_timeout=30s; server backend2.example.com; server backend3.example.com; } }
µÇ¼ºó¸´ÖÆ
ͨ¹ýÉèÖÃmax_failsºÍfail_timeout²ÎÊý£¬Nginx¿ÉÒÔ¶Ôºó¶ËЧÀÍÆ÷¾ÙÐпµ½¡¼ì²é£¬µ±Ä³¸öЧÀÍÆ÷Ò»Á¬Ê§°Ümax_fails´ÎÊýºó£¬½«ÔÝʱ±»±ê¼ÇΪ²»¿ÉÓã¬fail_timeout²ÎÊýÖ¸¶¨ÁËÏ´ÎʵÑéµÄʱ¼ä¾àÀë¡£
½áÓ
NginxÐéÄâÖ÷»ú¸ºÔØƽºâÉèÖÃÊÇʵÏÖ¶àÓòÃûÊ¿Á¿·Ö·¢µÄÖ÷Òª»·½Ú£¬Í¨¹ýºÏÀíµÄÉèÖã¬ÎÒÃÇ¿ÉÒÔÌá¸ßϵͳµÄ¿ÉÓÃÐÔºÍÐÔÄÜ¡£±¾ÎÄÌṩÁËÒ»¸ö»ù´¡µÄ¸ºÔØƽºâÉèÖÃʾÀý£¬²¢ÏÈÈÝÁËһЩ³£ÓõÄÉèÖÃÑ¡Ïî¡£¶ÁÕß¿ÉÒÔƾ֤ÏÖʵÐèÇó£¬ÎÞаµ÷½âÉèÖã¬ÒÔÖª×ã×Ô¼ºµÄÓªÒµÐèÇó¡£Ï£Íû±¾ÎĶԸ÷ÈËÔÚÉèÖÃNginxÐéÄâÖ÷»ú¸ºÔØƽºâʱÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇNginxÐéÄâÖ÷»ú¸ºÔØƽºâÉèÖã¬ÊµÏÖ¶àÓòÃûÊ¿Á¿·Ö·¢µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡