Nginx¸ºÔØƽºâËã·¨Ïê½â£¬ÓÅ»¯ÍøվЧÀÍ
nginx¸ºÔØƽºâËã·¨Ïê½â£¬ÓÅ»¯ÍøվЧÀÍ
СÐò£º
ÔÚ´óÐÍÍøÕ¾ÖУ¬ÎªÁËÌá¸ßÍøÕ¾µÄÐÔÄܺͿɿ¿ÐÔ£¬¾³£ÐèҪʹÓøºÔØƽºâÊÖÒÕ¡£NginxÊÇÒ»¿î¸ßÐÔÄܵĿªÔ´·´ÏòÊðÀíЧÀÍÆ÷£¬Ëü¿ÉÒÔ×÷Ϊ¸ºÔØƽºâЧÀÍÆ÷£¬½«¿Í»§¶ËÇëÇó·Ö·¢µ½¶ą̀ºó¶ËЧÀÍÆ÷¾ÙÐд¦Àí£¬´Ó¶øʵÏÖÍøÕ¾µÄ¸ß²¢·¢»á¼ûºÍ¹ÊÕÏתÒÆ¡£±¾ÎĽ«ÏêϸÏÈÈÝNginx¸ºÔØƽºâËã·¨£¬²¢ÇÒÌṩһЩ´úÂëʾÀý¡£
Ò»¡¢³£¼ûµÄ¸ºÔØƽºâËã·¨£º
ÂÖѯ£¨Round Robin£©£º½«¿Í»§¶ËÇëÇóÔȳƵطַ¢¸øºó¶ËЧÀÍÆ÷¡£µ±Ð§ÀÍÆ÷²î±ðµÄÐÔÄÜÆßÁã°ËÂäʱ£¬ÂÖѯËã·¨¿ÉÄÜÎÞ·¨µÖ´ïÀíÏëµÄ¸ºÔØƽºâЧ¹û£»
¼ÓȨÂÖѯ£¨Weighted Round Robin£©£ºÔÚÂÖѯËã·¨µÄ»ù´¡ÉϼÓÈëÁËȨÖصĿ´·¨£¬Í¨¹ýÉèÖÃȨÖØÖµ¿ÉÒÔµ÷½âºó¶ËЧÀÍÆ÷µÄ¸ºÔØƽºâ±ÈÀý£»
IP¹þÏ££¨IP Hash£©£ºÆ¾Ö¤¿Í»§¶ËµÄIPµØµã¾ÙÐйþÏ£ÅÌË㣬½«Í³Ò»¿Í»§¶ËµÄÇëÇó·Ö·¢µ½Í³Ò»ºó¶ËЧÀÍÆ÷£¬°ü¹ÜÁËͳһ¿Í»§¶ËÔÚÒ»¶Îʱ¼äÄÚ»á¼ûµÄÊÇͳһ̨ЧÀÍÆ÷£¬ÊÊÓÃÓÚ״̬¼á³ÖµÄÓ¦Óó¡¾°£»
×îÉÙÅþÁ¬£¨Least Connections£©£º½«ÇëÇó·Ö·¢µ½Ä¿½ñÅþÁ¬Êý×îÉٵĺó¶ËЧÀÍÆ÷£¬ÔÆÔÆ·Ö·¢¿ÉÒÔ×îºéÁ÷ƽÉÏ°ü¹Üºó¶ËЧÀÍÆ÷µÄ¸ºÔØƽºâ¡£
¶þ¡¢Nginx¸ºÔØƽºâÉèÖãº
ÒÔÏÂÊÇÒ»¸öʹÓÃ×îÉÙÅþÁ¬Ëã·¨µÄNginx¸ºÔØƽºâÉèÖÃʾÀý£º
ÐÞ¸Änginx.confÉèÖÃÎļþ£¬ÔÚhttp¿éÖÐÌí¼ÓÈçÏÂÄÚÈÝ£º
upstream backend { least_conn; #ʹÓÃ×îÉÙÅþÁ¬Ëã·¨ server backend1.example.com; server backend2.example.com; } server { listen 80; location / { proxy_pass http://backend; #ת·¢µ½backendºó¶ËЧÀÍÆ÷×é } }
µÇ¼ºó¸´ÖÆ
Ð޸ĺó¶ËЧÀÍÆ÷µÄÉèÖÃÎļþ£º
ÔÚÿ̨ºó¶ËЧÀÍÆ÷µÄnginx.confÉèÖÃÎļþÖУ¬Ö¸¶¨×ÔÉíµÄIPµØµãºÍ¶Ë¿ÚºÅ£¬ÈçÏÂËùʾ£º
server { listen 80; server_name backend1.example.com; ... } server { listen 80; server_name backend2.example.com; ... }
µÇ¼ºó¸´ÖÆ
Èý¡¢Nginx¸ºÔØƽºâÊÃ÷ÈÕ½£º
ÏÂÃæÒÔÒ»¸ö¼òÆÓµÄWebÓ¦ÓÃΪÀý£¬ÑÝʾNginx¸ºÔØƽºâµÄÏÖʵӦÓá£
±àдһ¸ö¼òÆÓµÄWebÓ¦Óãº
ÎÒÃÇʹÓÃPythonµÄFlask¿ò¼Ü±àдһ¸ö¼òÆÓµÄWebÓ¦Ó㬴úÂëÈçÏ£º
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello, World!" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
µÇ¼ºó¸´ÖÆ
Æô¶¯Á½¸öºó¶ËЧÀÍÆ÷£º
ÔÚÁ½Ì¨Ð§ÀÍÆ÷ÉÏ»®·ÖÔËÐÐÕâ¸öWebÓ¦Ó㬻®·Ö¼àÌý²î±ðµÄ¶Ë¿ÚºÅ¡£
ÐÞ¸ÄNginxÉèÖÃÎļþ£º
ÔÚNginxµÄÉèÖÃÎļþÖоÙÐÐÈçÏÂÉèÖãº
http { upstream backend { least_conn; server 192.168.0.1:5000; server 192.168.0.2:5000; } server { listen 80; location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
Æô¶¯NginxЧÀÍÆ÷£º
Æô¶¯NginxЧÀÍÆ÷£¬½«¿Í»§¶ËÇëÇóת·¢¸øÁ½Ì¨ºó¶ËЧÀÍÆ÷¾ÙÐд¦Àí¡£
½áÂÛ£º
ͨ¹ýNginx¸ºÔØƽºâËã·¨µÄÑ¡ÔñºÍÉèÖã¬ÎÒÃÇ¿ÉÒÔʵÏÖÍøÕ¾µÄ¸ß²¢·¢»á¼ûºÍ¹ÊÕÏתÒÆ£¬Ìá¸ßÁËÍøÕ¾µÄÐÔÄܺͿɿ¿ÐÔ¡£ÔÚÏÖʵӦÓÃÖУ¬Æ¾Ö¤ÏêϸµÄÐèÇóÑ¡ÔñÊʺϵĸºÔØƽºâËã·¨£¬²¢¾ÙÐÐÏìÓ¦µÄÉèÖ㬿ÉÒÔ×îºéÁ÷ƽµØÓÅ»¯ÍøÕ¾µÄЧÀÍ¡£
×ܽ᣺
±¾ÎÄÏêϸÏÈÈÝÁËNginx¸ºÔØƽºâËã·¨£¬²¢ÌṩÁËÏà¹ØµÄ´úÂëʾÀý¡£Ï£Íû¶ÁÕßͨ¹ýÔĶÁ±¾ÎÄ£¬¶ÔNginx¸ºÔØƽºâÓиüÉîÈëµÄÏàʶ£¬²¢ÄÜÔÚÏÖʵӦÓÃÖÐÎÞаÔËÓá£Í¬Ê±£¬Ò²Ï£Íû±¾ÎÄÄܹ»ÎªÍøÕ¾ÐÔÄÜÓÅ»¯ÌṩһЩ²Î¿¼ºÍÖ¸µ¼¡£
ÒÔÉϾÍÊÇNginx¸ºÔØƽºâËã·¨Ïê½â£¬ÓÅ»¯ÍøվЧÀ͵ÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡