ÔõÑùʹÓÃNginx¾ÙÐз´ÏòÊðÀíºÍ¸ºÔØƽºâ
ÔõÑùʹÓÃnginx¾ÙÐз´ÏòÊðÀíºÍ¸ºÔØƽºâ
¼ò½é£º
NginxÊÇÒ»¿î¸ßÐÔÄܵĿªÔ´WebЧÀÍÆ÷¼°·´ÏòÊðÀíЧÀÍÆ÷¡£Ëü²»µ«¿ÉÒÔÏñ¹Å°åWebЧÀÍÆ÷Ò»ÑùÌṩ¾²Ì¬ÎļþµÄЧÀÍ£¬»¹¿ÉÒÔ×÷Ϊ·´ÏòÊðÀíЧÀÍÆ÷£¬½«¿Í»§¶ËµÄÇëÇóת·¢¸øºó¶ËµÄ¶à¸öЧÀÍÆ÷£¬²¢ÊµÏÖ¸ºÔØƽºâ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃNginxʵÏÖ·´ÏòÊðÀíºÍ¸ºÔØƽºâµÄÉèÖá£
Ò»¡¢·´ÏòÊðÀí
·´ÏòÊðÀíÊÇÖ¸WebЧÀÍÆ÷ÎüÊÕ¿Í»§¶ËµÄÇëÇ󣬲¢½«Æäת·¢¸øºó¶ËµÄ¶à¸öЧÀÍÆ÷¡£¿Í»§¶ËÎÞ·¨Ö±½ÓÓëºó¶ËЧÀÍÆ÷½¨ÉèÅþÁ¬£¬Ö»ÄÜͨ¹ý·´ÏòÊðÀíЧÀÍÆ÷Óëºó¶ËЧÀÍÆ÷¾ÙÐÐͨѶ¡£·´ÏòÊðÀí¿ÉÒÔÒþ²Øºó¶ËЧÀÍÆ÷µÄÕæʵIPµØµã£¬Ìá¸ßϵͳµÄÇå¾²ÐÔ¡£
ÉèÖÃʾÀý£º
ÔÚNginxµÄÉèÖÃÎļþÖУ¬Ìí¼ÓÒ»¸öеÄserver¿éÀ´ÉèÖ÷´ÏòÊðÀí£º
server { listen 80; server_name example.com; location / { proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬listenÖ¸¶¨ÁËNginx¼àÌýµÄ¶Ë¿Ú£¬server_nameÖ¸¶¨ÁË·´ÏòÊðÀíµÄÓòÃû¡£location /ÌåÏÖ½«ËùÓеÄÇëÇó¶¼×ª·¢¸øºó¶ËЧÀÍÆ÷¡£proxy_passÉèÖúó¶ËЧÀÍÆ÷µÄµØµã£¬¿ÉÒÔÊÇIPµØµã»òÓòÃû¡£proxy_set_header¿ÉÒÔÉèÖÃһЩHTTPÍ·ÐÅÏ¢£¬ÈçHostºÍX-Real-IPµÈ¡£
¶þ¡¢¸ºÔØƽºâ
¸ºÔØƽºâÊÇÖ¸½«ÇëÇó·Ö·¢µ½¶à¸öºó¶ËЧÀÍÆ÷£¬ÒÔµÖ´ïÌá¸ßϵͳµÄÐÔÄܺͿÉÓÃÐÔµÄÄ¿µÄ¡£NginxÖ§³Ö¶àÖÖ¸ºÔØƽºâËã·¨£¬ÈçÂÖѯ¡¢¼ÓȨÂÖѯ¡¢×îÉÙÅþÁ¬µÈ¡£
ÉèÖÃʾÀý£º
ÔÚNginxµÄÉèÖÃÎļþÖУ¬Ìí¼ÓÒ»¸öеÄupstream¿éÀ´ÉèÖúó¶ËЧÀÍÆ÷£º
upstream backend_servers { server 192.168.0.1:8080; server 192.168.0.2:8080; server 192.168.0.3:8080; server 192.168.0.4:8080; } server { listen 80; server_name example.com; location / { proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬upstream¿é½ç˵Á˶à¸öºó¶ËЧÀÍÆ÷µÄµØµãºÍ¶Ë¿Ú¡£ÔÚlocation¿éÖУ¬proxy_passÉèÖÃupstream¿éµÄÃû³Æ£¬Nginx»áƾ֤ÉèÖõĸºÔØƽºâË㷨ѡÔñºÏÊʵĺó¶ËЧÀÍÆ÷¡£
Èý¡¢ÊµÏÖ¿µ½¡¼ì²é
ΪÁË°ü¹Üºó¶ËЧÀÍÆ÷µÄ¿ÉÓÃÐÔ£¬¿ÉÒÔÌí¼Ó¿µ½¡¼ì²éµÄ¹¦Ð§£¬µ±ºó¶ËЧÀÍÆ÷·ºÆð¹ÊÕÏʱ£¬Nginx»á×Ô¶¯½«ÇëÇóת·¢¸øÆäËûÕý³£µÄЧÀÍÆ÷¡£
ÉèÖÃʾÀý£º
ÔÚNginxµÄÉèÖÃÎļþÖУ¬¿ÉÒÔÌí¼ÓÒ»¸öеÄlocation¿éÀ´ÊµÏÖ¿µ½¡¼ì²é£º
location /check { access_log off; proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬location /checkÌåÏÖµ±ÇëÇó»á¼û/checkʱ£¬Nginx»á½«ÇëÇóת·¢¸øºó¶ËЧÀÍÆ÷£¬È»ºó¼ì²éÆä·µ»ØµÄ״̬Âë¡£ÈôÊÇ·µ»ØµÄ״̬ÂëΪerror¡¢timeout¡¢invalid_header¡¢http_500¡¢http_502¡¢http_503»òhttp_504ʱ£¬Nginx»á½«ÇëÇóת·¢¸øÆäËûÕý³£µÄЧÀÍÆ÷¡£
½áÂÛ£º
ͨ¹ýʹÓÃNginxµÄ·´ÏòÊðÀíºÍ¸ºÔØƽºâ¹¦Ð§£¬¿ÉÒÔÌá¸ßϵͳµÄÐÔÄܺͿÉÓÃÐÔ¡£Í¨¹ý±¾ÎĵÄÏÈÈݺʹúÂëʾÀý£¬ÐÅÍжÁÕßÒѾÏàʶÁËÔõÑùÉèÖÃNginx¾ÙÐз´ÏòÊðÀíºÍ¸ºÔØƽºâµÄÒªÁ죬ϣÍûÄܶԶÁÕßÔÚʵ¼ùÖÐÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginx¾ÙÐз´ÏòÊðÀíºÍ¸ºÔØƽºâµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡