Caching with Nginx

30 / Sep / 2016 by Nitesh Agarwal 0 comments

What is caching and why it is required?

Caching means storing information locally or in the memory for faster communication between our web browser and web server. It improves the response time of web page and improves the availability as a backup if an origin server failed.

Benefits of caching includes:

  • Improved site performance
  • Increased capacity
  • Greater availability

Use case

Our application is built on JAVA technologies and we use Tomcat to run our web server. In absence of any caching, tomcat is responsible for the required data to be shown on the page. To fasten up our process we used Nginx as a web cache. In addition to Nginx ability to serve static contents, it can serve as cache server when placed in front of application servers.

image nginx

How to set up Caching?

Only two directives are needed to enable caching:

  1. proxy_cache_path
  2. proxy_cache

2

Proxy_cache_path directives are:

/path/to/cache => local directory for the cache

levels => it is used for two-level directory structure which by default stores all files in the same directory.

keys_zone => It is a shared memory zone for storing cache keys and metadata. A 1 MB zone can store data for 8,000 keys.

max_size => It is optional; It is used to limit cache size. If the limit exceeds more than max_size a process called cache manager removes the least recent files to keep the size under the limit. If not specified than full disk space is used.

Inactive => It specifies how long item can stay in the cache without being accessed. Its default value is 10m (10 minutes); if a file is not requested for 10 minutes, then it will be deleted by cache manager process.

Example:imag2

In this example we have used key_zone directive is “one” and Its a shared memory zone named “one” with maximum size 10mb. Limit size up to 20 GB after that least recently item will be deleted and time for the inactive item to live is 30 minutes.

Size defined in key_zone does not limit the amount of cached response data. To limit the amount of cached response data, include the max_size parameter to the proxy_cache_path directive.

That’s All! See you with another write-up!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *