Install Memcached on Ubuntu 22.04 in 4 Easy Steps – OrcaCore

Posted on

Install Memcached on Ubuntu 22.04 in 4 Easy Steps - OrcaCore

Install Memcached on Ubuntu 22.04 in 4 Easy Steps – OrcaCore

This guide, brought to you by Orcacore, will walk you through the process of installing Install Memcached on Ubuntu 22.04. Memcached (pronounced mem-cash-dee or mem-cached) is a free and open-source, high-performance, distributed memory object caching system. Its primary use is to accelerate dynamic web applications by reducing the load on databases. Major websites dealing with massive amounts of data, like YouTube, Wikipedia, and Twitter, rely on Memcached for this purpose.

Memcached is favored in memory caching solutions due to its ease of installation on Windows and Unix-like systems. It boasts API integration for numerous programming languages, including PHP, Java, C/C++, Python, Ruby, and Perl.

Memcached stores data as key-value pairs, accommodating small, arbitrary strings or objects, including:

  • Results of database queries
  • API responses
  • Page fragments
  • Session data

Steps To Install and Configure Memcached on Ubuntu 22.04

Before proceeding, ensure you have a non-root user with sudo privileges on your server and a basic firewall configured. Refer to Orcacore’s guide, the Initial Server Setup with Ubuntu 22.04, for instructions on setting this up.

1. Install Memcached on Ubuntu 22.04

Begin by updating and upgrading your system packages:

sudo apt update && sudo apt upgrade -y

The Memcached packages are available in the default Ubuntu repository. Install Memcached using the following command:

sudo apt install memcached libmemcached-tools

Verify the installation by checking the package policy:

sudo apt-cache policy memcached

The output should resemble:

Install Memcached on Ubuntu 22.04

By default, Memcached should be active. Verify its status:

sudo systemctl status memcached
Memcached status Ubuntu 22.04

To ensure Memcached starts automatically on system boot, enable the service:

sudo systemctl enable memcached

Memcached listens on port 11211. Confirm this:

ps -ef | grep memcached
Memcached listening  port

2. Configure Memcached on Ubuntu 22.04

Now, configure Memcached by modifying its configuration file.

Open the configuration file using your preferred text editor (e.g., vi):

sudo vi /etc/memcached.conf

Examine the -l parameter. By default, it’s set to 127.0.0.1. If you need to allow connections from a local network or external IP, change this to the appropriate IP address.

-l 127.0.0.1

It is recommended to disable UDP unless it is specifically required:

-U 0

Adjust the -m parameter to a reasonable value for your server’s memory allocation:

-m 2000

Save the changes and close the file.

Restart Memcached to apply the new configuration:

sudo systemctl restart memcached

Configure Firewall for Memcached Caching System

If you are using UFW, create rules to allow traffic on TCP port 11211.

Allow access from any source:

sudo ufw allow 11211

Allow access from a specific IP address:

sudo ufw allow proto tcp from <ip address> to any port 11211

Allow access from a subnet:

sudo ufw allow proto tcp from <ip address>/24 to any port 11211

Note: Use the subnet rule cautiously, ensuring your internal network is secure.

Reload the firewall to apply the rules:

sudo ufw reload

3. Install PHP Extension For Memcached

Memcached has extensions for various programming languages, but it’s commonly used with PHP. Install the PHP extension:

sudo apt install php-memcached apache2 libapache2-mod-php php php-cli php-memcached php-memcached

Note: Apache users can enable Memcached with:

phpenmod memcached && sudo service apache2 restart

Install Additional Libraries on Ubuntu 22.04

You can install Python and Perl support as needed.

Python support:

sudo apt install python3-pymemcache

Perl support:

sudo apt install libcache-memcached-libmemcached-perl

4. Access Memcached from CLI

You can interact with Memcached directly from the command line.

Use Telnet to connect:

telnet localhost 11211
**Output**
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Get an overview of the Memcached service:

stats
**Output**
STAT pid 3012
STAT uptime 199
STAT time 1674666266
STAT version 1.6.14
STAT libevent 2.1.12-stable
STAT pointer_size 64
STAT rusage_user 0.074519
STAT rusage_system 0.068292
STAT max_connections 1024
STAT curr_connections 1
STAT total_connections 2
STAT rejected_connections 0
STAT connection_structures 2
STAT response_obj_oom 0
STAT response_obj_count 1
STAT response_obj_bytes 16384
STAT read_buf_count 2
STAT read_buf_bytes 32768
STAT read_buf_bytes_free 0
STAT read_buf_oom 0
STAT reserved_fds 20
STAT cmd_get 0
STAT cmd_set 0
STAT cmd_flush 0
...
END

List the slabs in the instance:

stats slabs

For more detailed information, refer to the Memcached Wikis page.

Conclusion

This guide on Install Memcached on Ubuntu 22.04 from Orcacore provided a step-by-step walkthrough on how to install and configure the Memcached caching system. You have now successfully completed the setup.

Hope you enjoyed it. You may also interested in these articles:

Install and Configure XWiki on Ubuntu 22.04

Install Joomla on Ubuntu 22.04

How To Install Wireshark on Ubuntu 22.04

Memcached Installation Steps on Debian 12

Installing and Configuring Memcached on AlmaLinux 9

Memcached setup Debian 11

Install Monit Manager on Debian 11

Fail2ban Setup on AlmaLinux 9

Alternative Solutions for Caching on Ubuntu 22.04

While Memcached is a robust and widely used solution, other caching mechanisms exist that might be more suitable depending on specific requirements. Here are two alternative approaches for caching on Ubuntu 22.04:

1. Redis

Redis (Remote Dictionary Server) is an in-memory data structure store, used as a database, cache, message broker, and streaming engine. Unlike Memcached, which primarily focuses on simple key-value storage, Redis offers a richer set of data structures, including lists, sets, sorted sets, and hashes. This makes it more versatile for complex caching scenarios.

Explanation:

Redis provides persistence options (RDB snapshots and AOF logging), meaning data can be saved to disk, preventing complete data loss in case of server failure. It also supports replication, enabling high availability and read scaling. Furthermore, Redis offers built-in support for pub/sub messaging, allowing for real-time data updates and event-driven architectures.

Installation and Basic Usage:

  1. Install Redis:

    sudo apt update
    sudo apt install redis-server
  2. Verify Installation:

    redis-cli ping

    If Redis is running correctly, the command will return "PONG".

  3. Basic Redis Operations (using redis-cli):

    # Set a key-value pair
    SET mykey "Hello Redis"
    
    # Get the value associated with a key
    GET mykey
    
    # Delete a key
    DEL mykey
  4. Code Example (Python with Redis):

    import redis
    
    # Connect to Redis
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    # Set a value
    r.set('mykey', 'Hello Redis from Python')
    
    # Get the value
    value = r.get('mykey')
    print(value.decode('utf-8')) # Output: Hello Redis from Python
    
    # Delete the key
    r.delete('mykey')

Redis is a powerful alternative to Install Memcached on Ubuntu 22.04 when you need more than just simple key-value caching, particularly if persistence, advanced data structures, or pub/sub functionality are required.

2. Varnish Cache

Varnish Cache is an HTTP accelerator designed for content-heavy dynamic websites. It sits in front of one or more web servers and caches HTTP responses in memory. When a client requests content, Varnish serves it directly from the cache if available, significantly reducing the load on the backend servers and improving response times.

Explanation:

Varnish is particularly effective for caching static content and frequently accessed dynamic content. Its Varnish Configuration Language (VCL) allows for highly customizable caching policies, enabling fine-grained control over which content is cached, how long it’s cached for, and how it’s served.

Installation and Basic Configuration:

  1. Install Varnish:

    sudo apt update
    sudo apt install varnish
  2. Configure Varnish (Basic):

    The default Varnish configuration is located in /etc/varnish/default.vcl. Edit this file to point Varnish to your backend web server.

    backend default {
        .host = "127.0.0.1";  # Your web server's IP address
        .port = "8080";       # Your web server's port (usually 80 or 8080)
    }
  3. Start Varnish:

    sudo systemctl start varnish
  4. Configure Apache/Nginx (Backend Server):

    Modify your web server configuration (Apache or Nginx) to listen on port 8080 (or the port you specified in the Varnish backend configuration). This ensures that traffic is routed through Varnish. For example, in Apache, you might change the Listen directive in /etc/apache2/ports.conf.

  5. Code Example (VCL Customization):

    This example shows how to set a custom TTL (Time To Live) for specific file types:

    sub vcl_deliver {
      if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
      } else {
        set resp.http.X-Cache = "MISS";
      }
      return (deliver);
    }
    
    sub vcl_backend_response {
      if (beresp.http.Content-Type ~ "image") {
        set beresp.ttl = 1h; # Cache images for 1 hour
      } else if (beresp.http.Content-Type ~ "text/css") {
        set beresp.ttl = 4h; # Cache CSS files for 4 hours
      } else {
        set beresp.ttl = 10m; # Default cache time of 10 minutes
      }
      return (deliver);
    }

Varnish is an excellent choice when optimizing the delivery of web content, particularly for sites with a high volume of traffic. Its ability to cache HTTP responses close to the client results in significant performance gains. Install Memcached on Ubuntu 22.04 is still a valid approach, but Varnish addresses caching at a different layer.

Leave a Reply

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