神刀安全网

Speed up Nodejs Application with Nginx proxy caching

“Don’t use #nodejs for static content”.

"Don’t use nodejs for static content" @trevnorris . If #nginx isn’t sitting in front of your node server, you’re probably doing it wrong.— Bryan Hughes August 30, 2014">@nebrius

Why caching ?

Caching help reduce request to upstream server. So improve performance site speed. Nginx so great for serve static content . So just let Nginx serve static content. It mean “Don’t use #nodejs for static content” . Just give this task for a web server like Nginx or Apache2.

Such as you store static content at /var/www/example.com/htdocs/assets/ so add this config to /etc/nginx/site-available/example.com

 location /assets {   alias /var/www/example.com/htdocs/assets;         access_log off;         expires max;  } 

And more than that: If data don’t change, so why we need to generate new html result: Just catch it use proxy_cache". Nginx will store response of Node app. All response now simple are just static content. Nginx will server this caching response, with less access times to Node app.

proxy_cache_path  /var/cache/nginx/exmaple.com  levels=1:2 keys_zone=ExampleSTATIC:100m inactive=24h max_size=2g;   proxy_cache  ExampleSTATIC;   proxy_cache_valid 200 10m;   proxy_cache_valid any 30s;   

You must sure that proxy cache path must exist

mkdir -p /var/cache/nginx/   

Then test nginx configure

nginx -t If no error message like this

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

*Full configuration *

upstream nodeapp {       server 127.0.0.1:port; }  proxy_cache_path /var/cache/nginx/example.com levels=1:2 keys_zone=ExampleSTATIC:75m inactive=24h max_size=512m;   server {      server_name example.com;  access_log   /var/log/nginx/example.com.access.log;         error_log    /var/log/nginx/example.com.error.log;     add_header X-Cache $upstream_cache_status;    location / {         proxy_cache ExampleSTATIC;         proxy_cache_valid 200 30m;         proxy_cache_valid 404 1m;         proxy_pass http://nodeapp;         proxy_ignore_headers X-Accel-Expires Expires Cache-Control;         proxy_ignore_headers Set-Cookie;         proxy_hide_header Set-Cookie;         proxy_hide_header X-powered-by;     }     location /assets/ {         alias /var/www/example.com/htdocs/assets/;         access_log off;         expires max;     }  } 

Finally, reload Nginx

service nginx reload   

For some Node app like Ghost is more complicate. You apply this: Self-hosted Ghost blog on Ubuntu/Debian

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Speed up Nodejs Application with Nginx proxy caching

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址