Sling Academy
Home/DevOps/Understanding Memcached in NGINX (with examples)

Understanding Memcached in NGINX (with examples)

Last updated: January 22, 2024

Introduction

Memcached is a high-performance, distributed memory caching system designed to speed up dynamic web applications by reducing database load. In conjunction with NGINX, a powerful web server and reverse proxy, Memcached can significantly improve the performance of a website by caching the results of database queries and serving them directly to clients without the need to repeatedly query the database.

In this tutorial, we will cover the basics of Memcached, discuss how it can be used with NGINX, and provide practical examples of integrating the two to enhance your web application’s efficiency.

Prerequisites

  • A server running Linux (Ubuntu, CentOS, etc.)
  • NGINX installed and configured on your server
  • Memcached installed on your server (install with sudo apt install memcached on Ubuntu)
  • Basic knowledge of Linux command line and server configurations

Getting Started

Step 1 – Installing Memcached

sudo apt update
sudo apt install memcached libmemcached-tools

After installing, ensure it’s running with:

systemctl status memcached

Step 2 – Configuring Memcached

Edit the default configuration file:

sudo nano /etc/memcached.conf

Adjust the memory usage and connection settings according to your needs. Here, ‘-m 64’ denotes 64MB of memory for Memcached to use:

-m 64
-u memcache
-p 11211
-l 127.0.0.1

Then restart Memcached:

sudo systemctl restart memcached

Step 3 – Configuring NGINX to Use Memcached

Open your site’s NGINX configuration:

sudo nano /etc/nginx/sites-available/your_site.conf

Inside the server block, add a location block for handling cached content:

location /cache_zone {
    set $memcached_key $uri;
    memcached_pass 127.0.0.1:11211;
    error_page 404 502 = @cache_miss;
}

location @cache_miss {
    proxy_pass http://backend;
}

This configuration attempts to retrieve the request URI from Memcached. If not found or on error, it proxies the request to the backend server.

Adding Memcached Support in Your Application

Your application should be configured to use Memcached. Here is how you might set up a simple cache in PHP:

$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);

$key = 'user-profile-' . $user_id;
$data = $memcached->get($key);

if ($data === FALSE) {
    // Data not found in cache, retrieve and set it
    $data = // ... fetch from database
    $memcached->set($key, $data, 60*60); // Cache for 1 hour
}

// Use $data

Caching Full Pages in Memcached

Your application can cache whole HTML pages. The following example illustrates how you can cache an entire page with PHP:

ob_start();

// Output your HTML
// ...

$html = ob_get_contents();
ob_end_flush();

$memcached->set($key, $html, 60*60); // Cache for 1 hour

Invalidating the Cache

To invalidate the cache, you can delete items by key:

// Invalidate cache
$memcached->delete($key);

Conclusion

Integrating Memcached with NGINX can lead to significant improvements in your application’s response time. It helps in handling high traffic and reduces the stress on your database by serving cached data to the clients. By leveraging the simple tips and methods discussed in this tutorial, you can begin optimizing your server configuration for better performance.

Next Article: Image Filter in NGINX: The Complete Guide

Previous Article: NGINX Charset Filter: The Developer’s Guide

Series: NGINX Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide