ÔõÑùʹÓÃNginx¾ÙÐÐHTTPÇëÇóµÄÖØÊԺ͹ÊÕÏתÒÆ
ÔõÑùʹÓÃnginx¾ÙÐÐhttpÇëÇóµÄÖØÊԺ͹ÊÕÏתÒÆ
ÔÚÏÖ´ú»¥ÁªÍøÓ¦ÓÃÖУ¬ÓÉÓÚ²»¿ÉÔ¤¼ûµÄÍøÂçÎÊÌâ»òºó¶ËЧÀ͵ĹÊÕÏ£¬ÎÒÃǾ³£»áÓöµ½HTTPÇëÇóʧ°ÜµÄÇéÐΡ£ÎªÁËÌá¸ßÓ¦ÓõĿÉÓÃÐÔºÍÎȹÌÐÔ£¬ÖØÊÔ»úÖƺ͹ÊÕÏתÒÆÊDZز»¿ÉÉٵġ£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃNginxÀ´ÊµÏÖHTTPÇëÇóµÄÖØÊԺ͹ÊÕÏתÒÆ¡£
ÖØÊÔ»úÖÆ
µ±Ò»¸öHTTPÇëÇóʧ°Üʱ£¬ÖØÊÔ»úÖÆ¿ÉÒÔÖØÐÂʵÑé·¢ËÍÇëÇó£¬Ö±µ½ÇëÇóÀֳɻòµÖ´ï×î´óÖØÊÔ´ÎÊý¡£ÔÚNginxÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃngx_http_proxy_moduleÄ£¿éÀ´ÊµÏÖHTTPÇëÇóµÄÖØÊÔ¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþÖÐÌí¼ÓÒ»¸ölocation¿é£¬ÓÃÓÚ½ç˵ÎÒÃÇÒª¾ÙÐÐÖØÊÔµÄÄ¿µÄµØµã¡£ÏÂÃæÊÇÒ»¸öʾÀýÉèÖãº
http { # ÆäËûÉèÖÃÏî server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_next_upstream error timeout; proxy_connect_timeout 1s; proxy_intercept_errors on; error_page 500 502 503 504 = @retry; } location @retry { internal; proxy_pass http://backend; proxy_next_upstream error timeout; } upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪbackendµÄupstreamÄ£¿é£¬ÆäÖаüÀ¨Á˶à¸öºó¶ËЧÀÍÆ÷µØµã¡£µ±ÏòÕâ¸öµØµã·¢ËÍHTTPÇëÇóʱ£¬ÈôÊDZ¬·¢¹ýʧ»ò³¬Ê±£¬Nginx»á×Ô¶¯ÖØÊÔÆäËûЧÀÍÆ÷¡£
ÉèÖÃÏîproxy_next_upstreamÓÃÓÚ½ç˵NginxÔÚÓöµ½¹ýʧ»ò³¬Ê±Ê±Çл»µ½ÏÂÒ»¸öºó¶ËЧÀÍÆ÷µÄÐÐΪ¡£errorÌåÏÖµ±Óöµ½5xx¼¶±ðµÄ¹ýʧʱÇл»£¬timeoutÌåÏÖµ±Óöµ½³¬Ê±¹ýʧʱÇл»¡£proxy_connect_timeoutÓÃÓÚÉèÖÃÅþÁ¬ºó¶ËЧÀÍÆ÷µÄ³¬Ê±Ê±¼ä¡£
¹ÊÕÏתÒÆ
µ±ºó¶ËЧÀÍÆ÷·ºÆð¹ÊÕÏʱ£¬ÎÒÃÇÐèÒª½«ÇëÇóת·¢µ½ÆäËû¿ÉÓõÄЧÀÍÆ÷ÉÏ¡£NginxÌṩÁËip_hashºÍupstreamÄ£¿éÀ´ÊµÏÖ¹ÊÕÏתÒÆ¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþÖнç˵һ¸öupstream¿é£¬Ö¸¶¨ºó¶ËЧÀÍÆ÷µÄµØµãºÍÆäËûÑ¡Ïî¡£ÏÂÃæÊÇÒ»¸öʾÀýÉèÖãº
http { # ÆäËûÉèÖÃÏî upstream backend { ip_hash; server backend1.example.com weight=1; server backend2.example.com weight=2; server backend3.example.com down; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÖУ¬ÎÒÃÇʹÓÃip_hashÑ¡ÏÇëÇóƾ֤¿Í»§¶ËIPµØµãת·¢µ½ºó¶ËЧÀÍÆ÷¡£ÕâÑùͳһ¸ö¿Í»§¶ËµÄÇëÇó»á±»·¢Ë͵½Í³Ò»¸öºó¶ËЧÀÍÆ÷£¬ÒÔ¼á³Ö»á»°µÄÒ»ÖÂÐÔ¡£Í¨¹ýweightÑ¡ÏÎÒÃÇ¿ÉÒÔ¸ø²î±ðµÄºó¶ËЧÀÍÆ÷·ÖÅɲî±ðµÄȨÖØ£¬ÓÃÓÚ¸ºÔØƽºâ¡£
µ±Ò»¸öºó¶ËЧÀÍÆ÷·ºÆð¹ÊÕÏʱ£¬¿ÉÒÔʹÓÃdownÑ¡ÏÆä±ê¼ÇΪ²»¿ÉÓã¬ÕâʱNginx»á×Ô¶¯½«ÇëÇóת·¢µ½ÆäËû¿ÉÓõÄЧÀÍÆ÷¡£
×ܽ᣺
ͨ¹ýÒÔÉϵÄÉèÖã¬ÎÒÃÇ¿ÉÒÔʹÓÃNginxÀ´ÊµÏÖHTTPÇëÇóµÄÖØÊԺ͹ÊÕÏתÒÆ¡£ÖØÊÔ»úÖÆ¿ÉÒÔÔÚÇëÇóʧ°Üʱ×Ô¶¯ÊµÑé¶à´Î£¬Ìá¸ßÁËÓ¦ÓõĿÉÓÃÐÔ¡£¹ÊÕÏתÒÆ»úÖÆ¿ÉÒÔÔÚºó¶ËЧÀÍÆ÷·ºÆð¹ÊÕÏʱ×Ô¶¯½«ÇëÇóת·¢µ½ÆäËû¿ÉÓõÄЧÀÍÆ÷ÉÏ£¬°ü¹ÜÁËÓ¦ÓõÄÎȹÌÐÔ¡£
ËäÈ»£¬ÒÔÉÏÖ»ÊÇ»ù±¾Ó÷¨µÄÏÈÈÝ£¬ÏÖʵӦÓÃÖпÉÄÜ»¹ÐèҪƾ֤ÏêϸÐèÇó¾ÙÐнøÒ»²½ÉèÖú͵÷ÓÅ¡£Ï£Íû±¾ÎĶÔÄãÃ÷È·ÔõÑùʹÓÃnginx¾ÙÐÐhttpÇëÇóµÄÖØÊԺ͹ÊÕÏתÒÆÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginx¾ÙÐÐHTTPÇëÇóµÄÖØÊԺ͹ÊÕÏתÒƵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡