FedoraRHEL Based

How To Install Memcached on Fedora 42

Install Memcached on Fedora 42

Memcached is a powerful, open-source memory caching system that significantly enhances the performance of dynamic websites by storing frequently accessed data in RAM. By reducing database load and speeding up applications, it has become an essential tool for developers and system administrators looking to optimize their web applications. This comprehensive guide walks you through installing and configuring Memcached on Fedora 42, providing all the necessary steps and best practices to get your caching system up and running efficiently.

Understanding Memcached and Its Benefits

Memcached functions as a distributed memory object caching system that stores data in memory on a key-value basis. Originally developed to enhance web application performance, Memcached caches API calls, database queries, and page rendering chunks in system memory, making them instantly accessible when needed.

The primary advantages of implementing Memcached include:

  • Reduced database load by minimizing redundant queries
  • Dramatically improved response times for dynamic content
  • Simplified scaling for high-traffic websites
  • Lower bandwidth consumption
  • Efficient resource utilization across distributed systems

Unlike traditional disk-based caching solutions, Memcached stores everything in RAM, enabling lightning-fast data retrieval while maintaining a lightweight footprint on your system.

Prerequisites for Installing Memcached on Fedora 42

Before proceeding with the Memcached installation, ensure your system meets these requirements:

  • A running Fedora 42 system with administrative (root) access
  • Terminal access to your server
  • Updated system packages
  • Basic understanding of Linux command line operations
  • Sufficient RAM for both your applications and Memcached cache

To prepare your system, first update all packages to their latest versions:

sudo dnf update -y

This ensures compatibility and security for your Memcached installation.

Installing Memcached on Fedora 42

Memcached is available in Fedora’s default repositories, making installation straightforward. Follow these steps to install the necessary components:

1. Open your terminal and run the update command:

sudo dnf update -y

2. Install Memcached and the libmemcached library:

sudo dnf install memcached libmemcached -y

The libmemcached package provides essential client libraries that many applications use to interact with Memcached.

3. After installation completes, start the Memcached service:

sudo systemctl start memcached

4. Enable Memcached to start automatically on system boot:

sudo systemctl enable memcached

5. Verify that Memcached is running properly:

sudo systemctl status memcached

You should see output indicating that Memcached is active and running. The output typically shows details about the process, including its PID, memory usage, and startup parameters.

Configuring Memcached for Optimal Performance

The default Memcached configuration works for basic usage, but optimizing it for your specific needs can significantly improve performance.

Basic Configuration Settings

The main configuration file for Memcached on Fedora 42 is located at /etc/sysconfig/memcached. You can view the default settings with:

cat /etc/sysconfig/memcached

You’ll see output similar to this:

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1"

These parameters control:

  • PORT: The TCP port Memcached listens on (default 11211)
  • USER: The system user that runs the Memcached process
  • MAXCONN: Maximum number of concurrent connections
  • CACHESIZE: Memory allocation in megabytes
  • OPTIONS: Additional command-line options

Customizing Your Configuration

To modify the configuration, edit the file using your preferred text editor:

sudo nano /etc/sysconfig/memcached

Common adjustments include:

1. Increasing memory allocation by changing CACHESIZE. For example, to allocate 1GB:

CACHESIZE="1024"

2. Adjusting maximum connections based on expected load:

MAXCONN="2048"

3. Binding to specific network interfaces for security (already set by default to localhost)

After making changes, save the file and restart Memcached:

sudo systemctl restart memcached

Starting and Managing the Memcached Service

Fedora 42 uses systemd to manage services, providing straightforward commands for controlling Memcached:

To start Memcached:

sudo systemctl start memcached

To stop Memcached:

sudo systemctl stop memcached

To restart Memcached after configuration changes:

sudo systemctl restart memcached

To check the current status:

sudo systemctl status memcached

To enable automatic startup:

sudo systemctl enable memcached

To disable automatic startup:

sudo systemctl disable memcached

You can also view Memcached logs to troubleshoot issues:

sudo journalctl -u memcached

These commands provide complete control over your Memcached service lifecycle.

Security Considerations for Memcached

Properly securing Memcached is critical to prevent unauthorized access and potential security issues, including amplification attacks.

Binding to Local Interface

By default, newer Fedora installations restrict Memcached to listen only on localhost (127.0.0.1), which prevents external access. This setting is defined in the OPTIONS parameter in the configuration file:

OPTIONS="-l 127.0.0.1,::1"

This configuration ensures that only applications running on the same server can access Memcached.

Disabling UDP

UDP support in Memcached can be exploited for amplification attacks. Disable UDP by adding the “-U 0” parameter to your OPTIONS line:

OPTIONS="-l 127.0.0.1,::1 -U 0"

This prevents attackers from using your Memcached instance in reflection attacks.

Firewall Configuration

Even with local binding, it’s good practice to configure your firewall to block external access to port 11211. For Fedora’s firewalld:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port protocol="tcp" port="11211" accept'
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv6" source address="::1" port protocol="tcp" port="11211" accept'
sudo firewall-cmd --reload

These measures collectively ensure that your Memcached instance remains secure while serving your applications.

Installing PHP Extensions for Memcached

If you’re using PHP applications with Memcached, you’ll need to install the appropriate PHP extensions.

Available PHP Extensions

There are two main PHP extensions for Memcached:

  1. php-pecl-memcache – An older, stable extension
  2. php-pecl-memcached – A newer extension with additional features that uses the libmemcached client library

The php-pecl-memcached extension generally offers more functionality and better performance for modern applications.

Installation Process

To install both extensions, run:

sudo dnf install php-pecl-memcache php-pecl-memcached -y

After installation, restart both Memcached and your web server (if applicable):

sudo systemctl restart memcached
sudo systemctl restart php-fpm  # If using PHP-FPM
sudo systemctl restart httpd    # If using Apache

Verifying the Installation

To verify that the PHP extensions are properly installed, create a simple PHP info script:

echo '<?php phpinfo(); ?>' | sudo tee /var/www/html/info.php

Then access this file through your web browser and search for “memcache” or “memcached”. You should see sections for both extensions if they’re properly installed.

Alternatively, you can check from the command line:

php -m | grep memcache

This should show the installed extension(s).

Testing Memcached Functionality

After installation and configuration, it’s important to verify that Memcached is functioning correctly.

Using Command Line Tools

The simplest test is to check if Memcached responds to basic commands:

echo "stats" | nc 127.0.0.1 11211

This command should return statistics about your Memcached instance, including uptime, connections, and memory usage.

Creating a PHP Test Script

For a more thorough test, create a PHP script that demonstrates basic Memcached operations:

<?php
// Create a Memcached instance
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);

// Test setting a value
$memcached->set('test_key', 'Hello, Memcached is working!', 60);

// Test retrieving the value
$value = $memcached->get('test_key');

// Output the result
echo "Retrieved value: " . $value;
?>

Save this as /var/www/html/memcached_test.php and access it through your web browser. If you see the message “Retrieved value: Hello, Memcached is working!”, your setup is functioning correctly.

Advanced Configuration Options

For high-traffic websites or specialized use cases, consider these advanced configuration options:

Memory Management

Adjust slab allocation by adding the growth factor parameter:

OPTIONS="-l 127.0.0.1,::1 -f 1.25"

This changes how memory is allocated between different sized objects, which can be tuned based on your application’s needs.

Connection Pooling

For high-concurrency environments, increase both MAXCONN and the number of threads:

MAXCONN="4096"
OPTIONS="-l 127.0.0.1,::1 -t 4"

The -t parameter specifies the number of threads Memcached will use, which should generally match the number of CPU cores available.

Session Storage Configuration

If using Memcached for PHP session storage, add these lines to your php.ini file:

session.save_handler = memcached
session.save_path = "127.0.0.1:11211"

This offloads session storage from the filesystem to Memcached, improving performance for busy web applications.

Troubleshooting Common Issues

Even with careful setup, you might encounter issues with your Memcached installation. Here are solutions to common problems:

Connection Refused Errors

If applications can’t connect to Memcached, check:

1. Memcached service status:

sudo systemctl status memcached

2. Proper binding configuration:

ss -antpl | grep memcached

3. Firewall settings:

sudo firewall-cmd --list-all

Memory Allocation Problems

If Memcached isn’t caching effectively or is evicting items too quickly:

1. Check current memory usage:

echo "stats" | nc 127.0.0.1 11211 | grep bytes

2. Increase CACHESIZE in the configuration file

3. Restart Memcached after changes

PHP Extension Issues

If PHP can’t connect to Memcached:

1. Verify extension installation:

php -m | grep memcache

2. Check PHP error logs:

sudo tail -f /var/log/php-fpm/www-error.log  # for PHP-FPM
sudo tail -f /var/log/httpd/error_log        # for Apache

3. Ensure PHP and Memcached are both running and properly configured

Performance Monitoring and Optimization

To get the most out of Memcached, regular monitoring and optimization are essential.

Key Metrics to Monitor

Track these important metrics to ensure optimal performance:

  • Hit rate: The percentage of requests that are served from cache
  • Memory usage: How much of the allocated memory is being used
  • Evictions: Items removed from cache due to memory constraints
  • Connections: Number of active client connections

You can view these metrics using:

echo "stats" | nc 127.0.0.1 11211

Third-Party Monitoring Tools

Consider using dedicated tools for more comprehensive monitoring:

  • Memcached-tool: A command-line utility included with Memcached
  • Cacti or Grafana: For graphical monitoring and alerting
  • Prometheus with exporters: For comprehensive metrics collection

These tools provide insights into performance trends and help identify optimization opportunities.

Congratulations! You have successfully installed Memcached. Thanks for using this tutorial for installing the Memcached on your Fedora 42 Linux system. For additional help or useful information, we recommend you check the official Memcached website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button