有做過網頁速度優化的工程師,應該對於 cache 相當熟悉,適當的增加 cache 可以大幅地減少 server 的負擔。

甚至在後端我們也常用 redis 去 cache 一些常用或計算負擔較重的資料.

在使用 nodejs 做開發時,我們時常會需要使用到 web server 的 reverse proxy 功能。

這篇主要想記錄如何開啟 nginx 的 proxy_cache,減少 Reverse Proxy Server 打到後面的 web server 的 request 數量,也是類似於 varnish 所做的功能

 

  1. 找到 nginx.conf 檔案,預設會在 /etc/nginx/nginx.conf
  2. 設定 cache 檔案的存放位置及 expired 等資訊,這邊先以 my_cache 為 key 去更新 cache
    proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m;
  3. 在想套用的 reverse proxy location 新增 proxy_cache,例如 @express
    location @express {
      # nginx proxy cache
      proxy_cache my_cache;
      proxy_cache_valid 10s;
    
      proxy_pass http://localhost:3000;
    }
    

     

  4. 以上這樣就會在 reverse proxy 先做一層 cache,減少打到 express 的 request  數量
  5. 若希望特定的 location 不使用 proxy cache 可以用 no-cache,像是 /api 都不 cache
    location /api/ {
      set $nocache 1;
      proxy_no_cache $nocache;
      proxy_cache_bypass $nocache;
      proxy_cache_valid 0s;
      proxy_pass http://localhost:3000;
    }
    

 

參考資料:

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache

 

 

Leave a Reply