NginxЧÀÍÆ÷¼Ü¹¹Éè¼Æ¼°ÐÔÄÜÓÅ»¯Ïê½â
nginxЧÀÍÆ÷¼Ü¹¹Éè¼Æ¼°ÐÔÄÜÓÅ»¯Ïê½â
ͻ񻣼
NginxÊÇÒ»¸öÇáÁ¿¼¶¸ßÐÔÄܵÄWebЧÀÍÆ÷Èí¼þ£¬±»ÆÕ±éÓ¦ÓÃÓÚ´óÐÍÍøÕ¾ºÍ»¥ÁªÍøÓ¦ÓÃÖС£±¾ÎĽ«ÏÈÈÝNginxµÄЧÀÍÆ÷¼Ü¹¹Éè¼ÆÒÔ¼°ÐÔÄÜÓÅ»¯µÄÏêϸҪÁ죬²¢¸½´ø´úÂëʾÀý¡£
ЧÀÍÆ÷¼Ü¹¹Éè¼Æ
Nginx½ÓÄɵÄÊǶàÀú³ÌºÍÒì²½ÊÂÎñÇý¶¯µÄ¼Ü¹¹£¬¿ÉÒÔ³ä·ÖʹÓöàºËCPUµÄÓÅÊÆ£¬Ìá¸ßϵͳµÄ²¢·¢´¦Öóͷ£ÄÜÁ¦¡£ÆäÖ÷Òª·ÖΪMasterÀú³ÌºÍWorkerÀú³ÌÁ½¸öÌõÀí¡£
1.1 MasterÀú³Ì
MasterÀú³ÌÊÇNginxµÄÖ÷¿ØÀú³Ì£¬ÈÏÕæÖÎÀíËùÓÐWorkerÀú³Ì£¬²¢´¦Öóͷ£HTTPÇëÇóµÄ·Ö·¢ºÍµ÷Àí¡£ÏêϸÀ´Ëµ£¬MasterÀú³ÌÖ÷ÒªÍê³ÉÒÔÏÂÊÂÇ飺
1£©¶ÁÈ¡Ï¢ÕùÎöÉèÖÃÎļþ£¬³õʼ»¯Ð§ÀÍÆ÷£»
2£©Æô¶¯WorkerÀú³Ì£¬²¢ÓëÖ÷Àú³Ì¾ÙÐÐͨѶ£»
3£©¼àÌýÍøÂçÊÂÎñ£¬ÎüÊÕÀ´×Ô¿Í»§¶ËµÄÅþÁ¬ÇëÇó£»
4£©·Ö·¢ÇëÇóµ½²î±ðµÄWorkerÀú³Ì¡£
1.2 WorkerÀú³Ì
WorkerÀú³ÌÊÇNginxµÄÊÂÇéÀú³Ì£¬ÈÏÕæ´¦Öóͷ£ÏêϸµÄHTTPÇëÇóºÍÏìÓ¦¡£Ã¿¸öWorkerÀú³Ì×ÔÁ¦ÔËÐУ¬Ï໥֮¼ä²»»á×ÌÈÅ¡£WorkerÀú³ÌµÄÖ÷ÒªÊÂÇé°üÀ¨£º
1£©ÎüÊÕMasterÀú³Ì·Ö·¢µÄÇëÇó£»
2£©´¦Öóͷ£ÇëÇ󣬰üÀ¨¶ÁÈ¡ÇëÇó±¨ÎÄ¡¢ÆÊÎöÇëÇóÍ·ºÍURLµÈ£»
3£©Å²ÓÃÏà¹ØÄ£¿é´¦Öóͷ£ÇëÇ󣬲¢ÌìÉúÏìÓ¦±¨ÎÄ£»
4£©½«ÏìÓ¦·¢Ë͸ø¿Í»§¶Ë¡£
ÐÔÄÜÓÅ»¯ÒªÁì
ΪÁ˽øÒ»²½Ìá¸ßNginxµÄÐÔÄÜ£¬ÎÒÃÇ¿ÉÒÔ´ÓÒÔϼ¸¸ö·½Ãæ¾ÙÐÐÓÅ»¯¡£
2.1 ÓÅ»¯NginxÉèÖÃ
NginxµÄÐÔÄÜÓÅ»¯´ÓÓÅ»¯ÉèÖÃÎļþ×îÏÈ¡£Ö÷ÒªÉæ¼°ÒÔϼ¸¸ö·½Ã棺
1£©worker_processes²ÎÊý£ºÉèÖÃWorkerÀú³ÌÊýÄ¿£¬Æ¾Ö¤Ð§ÀÍÆ÷µÄCPU½¹µãÊýÀ´¾öÒ飻
2£©worker_connections²ÎÊý£ºÉèÖÃÿ¸öWorkerÀú³ÌµÄ×î´ó²¢·¢ÅþÁ¬Êý£¬Æ¾Ö¤Ð§ÀÍÆ÷µÄÓ²¼þ×ÊÔ´À´µ÷½â£»
3£©keepalive_timeout²ÎÊý£ºÉèÖó¤ÅþÁ¬µÄ³¬Ê±Ê±¼ä£¬ïÔÌTCPÅþÁ¬ÆµÈÔ½¨ÉèºÍ¹Ø±ÕµÄ¿ªÏú¡£
2.2 ʹÓûº´æ»úÖÆ
NginxÖ§³Ö½«¾²Ì¬Îļþ»º´æµ½ÄÚ´æÖУ¬ÒÔïÔÌ´ÅÅÌIOµÄ¿ªÏú¡£Í¨¹ýÉèÖÃÈçϵÄCacheÖ¸Á¿ÉÒÔÆôÓûº´æ»úÖÆ£º
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m;
µÇ¼ºó¸´ÖÆ
2.3 ¸ºÔØƽºâ
NginxÄÚÖÃÁ˸ºÔØƽºâµÄ¹¦Ð§£¬¿ÉÒÔͨ¹ýÉèÖÃupstreamÀ´ÊµÏÖ¸ºÔØƽºâ¡£ÏêϸµÄÉèÖÃÈçÏÂËùʾ£º
upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; }
µÇ¼ºó¸´ÖÆ
2.4 ¿ªÆôGzipѹËõ
ʹÓÃGzipѹËõ¿ÉÒÔ¼õСÏìÓ¦±¨ÎĵÄÌå»ý£¬½ÚÔ¼ÍøÂç´ø¿í¡£Í¨¹ýÉèÖÃÈçϵÄGzipÖ¸Á¿ÉÒÔÆôÓÃGzipѹËõ£º
gzip on; gzip_types text/plain text/css application/json;
µÇ¼ºó¸´ÖÆ
2.5 ÏÞÁ÷Óë±ÜÃâDDoS¹¥»÷
Nginx¿ÉÒÔͨ¹ýÉèÖÃlimit_connºÍlimit_reqÄ£¿éÀ´ÏÞÖÆ¿Í»§¶ËµÄ²¢·¢ÅþÁ¬ÊýºÍÇëÇóƵÂÊ£¬ÒÔ±ÜÃâ¶ñÒâÇëÇóÒý·¢µÄЧÀÍÆ÷¸ºÔعý¸ß¡£ÏêϸµÄÉèÖÃÈçÏÂËùʾ£º
limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10; limit_req_zone $binary_remote_addr zone=addr:10m rate=10r/s; limit_req zone=addr burst=20;
µÇ¼ºó¸´ÖÆ
½áÂÛ£º
ͨ¹ýºÏÀíµÄЧÀÍÆ÷¼Ü¹¹Éè¼ÆºÍÐÔÄÜÓÅ»¯ÒªÁ죬¿ÉÒÔ´ó´óÌá¸ßNginxµÄÐÔÄܺÍÎȹÌÐÔ£¬ÊµÏÖ¸üºÃµÄWebЧÀÍ¡£ÉÏÊöËùʾµÄ´úÂëʾÀý¼´¿É×÷ΪÏÖʵÏîÄ¿µÄ²Î¿¼£¬×ÊÖú¿ª·¢Ö°Ô±¸üºÃµØÃ÷È·ºÍÓ¦ÓÃNginx¡£
²Î¿¼ÎÄÏ×£º
Nginx Documentation [Online]. Available: https://nginx.org/en/docs/
Richard Ou. (2015). Scaling Nginx: Load Balancing and Microcaching with Nginx [Online]. Available: https://www.nginx.com/blog/scaling-nginx-load-balancing-microcaching-nginx/
Nginx Performance [Online]. Available: https://www.nginx.com/blog/tuning-nginx/
ÒÔÉϾÍÊÇNginxЧÀÍÆ÷¼Ü¹¹Éè¼Æ¼°ÐÔÄÜÓÅ»¯Ïê½âµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡