RHEL BasedRocky Linux

How To Install Memcached on Rocky Linux 10

Install Memcached on Rocky Linux 10

Memcached stands as one of the most powerful and widely-adopted distributed memory caching systems in modern web infrastructure. This high-performance, open-source solution dramatically improves application response times by storing frequently accessed data in RAM, reducing database load and enhancing user experience across web applications.

Major technology companies including Facebook, YouTube, and Twitter rely on Memcached to handle millions of requests efficiently. The system operates as an in-memory key-value store, making data retrieval lightning-fast compared to traditional disk-based storage solutions. When properly implemented, Memcached can reduce database queries by up to 90% while improving page load times significantly.

Rocky Linux 10, as an enterprise-grade operating system, provides the perfect foundation for deploying Memcached in production environments. Its stability, security features, and long-term support make it an ideal choice for mission-critical applications requiring reliable caching infrastructure.

This comprehensive guide walks you through every step of installing, configuring, and optimizing Memcached on Rocky Linux 10. You’ll learn essential configuration techniques, security best practices, performance tuning strategies, and troubleshooting methods that ensure your caching layer operates at peak efficiency. Whether you’re managing a small web application or enterprise-level infrastructure, this tutorial provides the knowledge needed to implement Memcached successfully.

Prerequisites and System Requirements

Before beginning the Memcached installation process, ensure your Rocky Linux 10 environment meets specific requirements for optimal performance and compatibility.

System Specifications:
Your server should have at least 1GB of RAM, though 2GB or more is recommended for production environments. Memcached’s performance directly correlates with available memory since it stores all cached data in RAM. CPU requirements are minimal, but multi-core processors handle concurrent connections more effectively.

Access Requirements:
Root or sudo privileges are essential for installing packages and modifying system configurations. SSH access to your Rocky Linux 10 server enables remote management and configuration. Ensure your user account has appropriate permissions to execute system-level commands.

Network Configuration:
Stable network connectivity is crucial for both installation and operation. Default Memcached installations use port 11211, which should be available and not blocked by existing services. Consider firewall implications early in your planning process.

Knowledge Prerequisites:
Basic command-line proficiency helps navigate the installation process smoothly. Familiarity with text editors like vi, nano, or emacs proves useful when modifying configuration files. Understanding of Linux service management concepts enhances troubleshooting capabilities.

Understanding Memcached Architecture

Memcached operates on a simple yet powerful distributed caching architecture that stores data as key-value pairs in memory. This design eliminates disk I/O bottlenecks that typically slow database operations, resulting in sub-millisecond response times for cached data retrieval.

Core Architecture Principles:
The system uses a hash table structure where each piece of data is associated with a unique key. When applications request data, Memcached first checks its memory store before falling back to slower storage systems. This approach dramatically reduces database load while improving application responsiveness.

Multi-Threading Capabilities:
Memcached leverages multi-threading to handle multiple client connections simultaneously. Each thread can process requests independently, allowing the system to scale vertically by utilizing additional CPU cores effectively. This architecture supports thousands of concurrent connections on properly configured systems.

Network Communication:
By default, Memcached listens on port 11211 using TCP protocol. The service accepts connections from configured network interfaces, enabling distributed caching across multiple application servers. Proper network configuration ensures secure and efficient communication between clients and cache servers.

Memory Management:
Memcached implements sophisticated memory allocation algorithms that efficiently manage available RAM. When memory limits are reached, the system uses a Least Recently Used (LRU) eviction policy to remove older data and make space for new entries. This automatic management prevents memory overflow while maintaining cache effectiveness.

Preparing Rocky Linux 10 for Installation

System preparation creates a clean foundation for Memcached installation while ensuring all dependencies are properly configured.

Updating System Packages:
Begin by updating all existing packages to their latest versions. This step prevents compatibility issues and ensures security patches are current:

sudo dnf update -y

The update process may take several minutes depending on your system’s current state and available updates. Allow the process to complete fully before proceeding.

Installing Development Tools:
Essential development tools and libraries support Memcached compilation and operation. Install the required packages using DNF:

sudo dnf groupinstall "Development Tools" -y
sudo dnf --enablerepo=crb install libmemcached-awesome libmemcached-awesome-tools libmemcached-awesome-devel -y

These packages provide necessary libraries and tools for both Memcached operation and client application development.

Enabling Additional Repositories:
Rocky Linux 10 includes most required packages in default repositories. However, enabling the CRB (Code Ready Builder) repository ensures access to additional development libraries that may be needed for advanced configurations.

User Account Configuration:
Create a dedicated non-root user account for enhanced security practices. This account should have sudo privileges for administrative tasks while limiting direct root access:

sudo useradd -m memcache-admin
sudo usermod -aG wheel memcache-admin

Verification Steps:
Confirm your system is ready by checking available disk space, memory capacity, and network connectivity. These verification steps prevent installation issues and identify potential problems early in the process.

Installing Memcached on Rocky Linux 10

The installation process utilizes Rocky Linux’s DNF package manager to install Memcached and its supporting libraries efficiently.

Core Package Installation:
Install the main Memcached package along with essential libraries:

sudo dnf install memcached libmemcached -y

This command downloads and installs the latest stable version of Memcached available in Rocky Linux 10 repositories. The installation process typically completes within a few minutes, depending on your internet connection speed.

Verifying Installation Success:
Confirm the installation completed successfully by checking package information:

rpm -qi memcached

This command displays detailed package information including version number, architecture, installation date, and vendor details. Successful output indicates proper package installation.

Understanding Installation Directories:
Memcached installation creates several important directories and files:

  • Binary Location: /usr/bin/memcached contains the main executable
  • Configuration: /etc/sysconfig/memcached stores service configuration
  • Service File: /usr/lib/systemd/system/memcached.service defines systemd service parameters
  • Documentation: /usr/share/doc/memcached/ contains help files and examples

Additional Tools Installation:
Install supplementary tools that aid in Memcached management and debugging:

sudo dnf install memcached-devel nc telnet -y

These tools provide command-line utilities for testing connections, debugging issues, and developing applications that integrate with Memcached.

Version Verification:
Check the installed Memcached version to ensure compatibility with your applications:

memcached -h | head -n 1

Document this version information for future reference and compatibility planning with client libraries and applications.

Configuring Memcached

Proper configuration optimizes Memcached performance while ensuring security and reliability in production environments.

Main Configuration File:
Edit the primary configuration file located at /etc/sysconfig/memcached:

sudo nano /etc/sysconfig/memcached

Understanding Configuration Parameters:
The configuration file contains several critical parameters that control Memcached behavior:

PORT Configuration:

PORT="11211"

The default port 11211 works well for most installations. Change this value only if port conflicts exist or security policies require non-standard ports.

User Account Settings:

USER="memcached"

The memcached user account provides security isolation by running the service under a dedicated user rather than root. This configuration minimizes security risks from potential vulnerabilities.

Connection Limits:

MAXCONN="1024"

Maximum connection limits control how many simultaneous clients can connect. Increase this value for high-traffic applications, but monitor system resources to prevent overload.

Memory Allocation:

CACHESIZE="128"

Cache size determines how much RAM Memcached uses for data storage. Allocate 25-50% of total system RAM for cache, leaving sufficient memory for the operating system and other services.

Network Interface Binding:

OPTIONS="-l 127.0.0.1,::1 -S"

This configuration binds Memcached to localhost interfaces only, providing security by preventing external connections. Modify these settings carefully when enabling network access.

Advanced Security Options:
Enable SASL authentication for enhanced security in network-accessible installations:

OPTIONS="-l 127.0.0.1,::1 -S -vv"

The -S flag enables SASL support, while -vv provides verbose logging for debugging purposes.

Production Configuration Example:
For production environments, use optimized settings that balance performance and security:

PORT="11211"
USER="memcached"
MAXCONN="2048"
CACHESIZE="512"
OPTIONS="-l 127.0.0.1 -S -m 512 -c 2048"

Configuration Validation:
Test configuration syntax before restarting services by running Memcached in test mode:

sudo -u memcached memcached -f /etc/sysconfig/memcached -t

This command validates configuration parameters without starting the actual service, preventing startup failures due to configuration errors.

Managing Memcached Service

Effective service management ensures Memcached operates reliably and starts automatically after system reboots.

Starting Memcached Service:
Initialize the Memcached service using systemd:

sudo systemctl start memcached

This command starts Memcached immediately using current configuration settings. The service begins listening on the configured port and is ready to accept connections.

Enabling Auto-Start:
Configure Memcached to start automatically during system boot:

sudo systemctl enable memcached

Auto-start configuration ensures cache availability after unexpected reboots or planned maintenance windows.

Service Status Monitoring:
Check service status and health information:

sudo systemctl status memcached

Status output includes process ID, memory usage, startup time, and recent log entries. Green “active (running)” status indicates successful service operation.

Service Restart Procedures:
Restart Memcached after configuration changes:

sudo systemctl restart memcached

Restarting applies new configuration parameters and clears all cached data. Plan restarts during maintenance windows to minimize application impact.

Viewing Service Logs:
Monitor service logs for errors, warnings, and operational information:

sudo journalctl -u memcached -f

Log monitoring helps identify performance issues, connection problems, and security events that require attention.

Graceful Service Shutdown:
Stop Memcached service when maintenance or troubleshooting requires:

sudo systemctl stop memcached

Graceful shutdown allows existing connections to complete while preventing new connections, minimizing service disruption.

Firewall Configuration and Security

Implementing proper firewall rules and security measures protects Memcached from unauthorized access while enabling legitimate connections.

Opening Required Ports:
Configure firewalld to allow Memcached traffic:

sudo firewall-cmd --permanent --add-port=11211/tcp
sudo firewall-cmd --reload

These commands permanently open port 11211 for TCP connections and immediately apply the changes.

Verifying Firewall Rules:
Confirm firewall configuration includes the new rule:

sudo firewall-cmd --list-ports

Output should include “11211/tcp” among the allowed ports, confirming proper firewall configuration.

Restricting Source IP Addresses:
For enhanced security, limit access to specific IP addresses or subnets:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="11211" accept'
sudo firewall-cmd --reload

This configuration allows access only from the specified subnet, blocking all other connection attempts.

Implementing SASL Authentication:
Enable SASL authentication for network-accessible installations:

sudo dnf install cyrus-sasl-devel cyrus-sasl-lib -y

Configure SASL settings in /etc/sysconfig/memcached by adding authentication parameters to the OPTIONS line.

SSL/TLS Encryption:
While Memcached doesn’t natively support SSL, implement encryption using stunnel or similar tools for sensitive data transmission. This approach provides an encrypted tunnel for Memcached communications.

Regular Security Updates:
Maintain system security by regularly updating packages:

sudo dnf update memcached -y

Security updates address vulnerabilities and improve overall system security posture.

Access Control Best Practices:

  • Use dedicated network segments for cache traffic
  • Implement monitoring and alerting for unusual connection patterns
  • Regularly audit user accounts and permissions
  • Deploy intrusion detection systems for comprehensive security

Testing and Verification

Thorough testing validates Memcached installation and confirms proper operation across various scenarios.

Basic Connection Testing:
Test local connectivity using telnet:

telnet localhost 11211

Successful connection displays a telnet prompt where you can execute Memcached commands directly. Type quit to exit the telnet session.

Command-Line Statistics:
Retrieve Memcached statistics using netcat:

echo "stats" | nc localhost 11211

Statistics output includes memory usage, connection counts, cache hits/misses, and other operational metrics that indicate system health.

Basic Cache Operations:
Test fundamental cache functionality by storing and retrieving data:

echo -e "set test_key 0 3600 5\r\nhello\r\nquit" | nc localhost 11211
echo -e "get test_key\r\nquit" | nc localhost 11211

These commands store a value with the key “test_key” and retrieve it, confirming basic cache operations work correctly.

Performance Benchmarking:
Use memcached-tool for performance analysis:

memcached-tool localhost:11211 stats

Performance metrics help establish baseline measurements for capacity planning and optimization efforts.

Memory Usage Monitoring:
Monitor memory allocation and usage patterns:

memcached-tool localhost:11211 display

Memory statistics reveal cache efficiency, eviction rates, and available capacity for additional data.

Network Connectivity Validation:
Test remote connections if network access is configured:

telnet your-server-ip 11211

Replace “your-server-ip” with the actual server IP address to verify network accessibility from remote clients.

Integration with Applications

Successful application integration leverages Memcached’s caching capabilities to improve performance across various programming languages and frameworks.

PHP Integration:
Install the PHP Memcached extension:

sudo dnf install php-pecl-memcached -y

Basic PHP code for cache operations:

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

// Store data
$memcached->set('user_123', $user_data, 3600);

// Retrieve data
$cached_data = $memcached->get('user_123');
if ($cached_data === false) {
    // Cache miss - fetch from database
    $user_data = fetch_from_database();
    $memcached->set('user_123', $user_data, 3600);
}
?>

Python Integration:
Install the Python Memcached library:

sudo dnf install python3-memcached -y

Python implementation example:

import memcache

mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set('key', 'value', time=3600)
retrieved_value = mc.get('key')

Session Storage Configuration:
Configure web applications to store sessions in Memcached for improved performance and scalability. This approach enables session sharing across multiple application servers.

Connection Pooling:
Implement connection pooling in high-traffic applications to efficiently manage Memcached connections and reduce connection overhead.

Error Handling Strategies:
Develop robust error handling that gracefully degrades when cache services are unavailable, ensuring application functionality continues even during cache maintenance.

Caching Patterns:
Implement effective caching patterns such as:

  • Cache-aside: Application manages cache population and invalidation
  • Write-through: Data writes update both cache and database simultaneously
  • Write-behind: Cache updates occur immediately, database updates happen asynchronously

Performance Optimization

Optimizing Memcached performance requires careful tuning of memory allocation, connection settings, and monitoring key performance indicators.

Memory Management Optimization:
Calculate optimal cache size based on application requirements and available system resources. Monitor memory usage patterns to identify optimal allocation:

echo "stats slabs" | nc localhost 11211

Slab statistics reveal memory utilization efficiency and help identify potential fragmentation issues.

Connection Tuning:
Adjust maximum connections based on application load:

sudo nano /etc/sysconfig/memcached

Increase MAXCONN values for high-traffic applications, but monitor system resources to prevent overload conditions.

Network Buffer Optimization:
Tune TCP socket buffers for improved network performance:

OPTIONS="-l 127.0.0.1 -S -R 4096"

The -R parameter sets the maximum number of requests per event, improving throughput for batch operations.

Threading Configuration:
Optimize thread usage for multi-core systems:

OPTIONS="-l 127.0.0.1 -S -t 4"

The -t parameter specifies the number of threads to use, typically matching the number of CPU cores.

Monitoring Key Performance Indicators:
Track essential metrics including:

  • Cache hit ratio (aim for >80%)
  • Memory utilization (monitor for efficient allocation)
  • Connection counts (ensure adequate capacity)
  • Eviction rates (minimize premature data removal)

Performance Monitoring Tools:
Implement monitoring solutions that track Memcached performance over time:

watch -n 5 'echo "stats" | nc localhost 11211 | grep -E "(cmd_get|cmd_set|get_hits|get_misses)"'

This command displays cache statistics every 5 seconds, enabling real-time performance monitoring.

Maintenance and Monitoring

Regular maintenance ensures optimal Memcached performance while proactive monitoring identifies issues before they impact applications.

Scheduled Maintenance Tasks:
Establish regular maintenance routines including:

  • Weekly system updates and security patches
  • Monthly configuration backups
  • Quarterly performance reviews and optimization
  • Annual capacity planning assessments

Health Monitoring Implementation:
Deploy monitoring solutions that track service availability:

#!/bin/bash
if ! echo "version" | nc localhost 11211 > /dev/null 2>&1; then
    echo "Memcached service is down"
    # Send alert or restart service
fi

Log Rotation Configuration:
Configure log rotation to manage disk space:

sudo nano /etc/logrotate.d/memcached

Proper log management prevents disk space issues while maintaining operational history.

Backup Procedures:
While Memcached data is transient, backup configuration files and monitoring scripts:

sudo cp /etc/sysconfig/memcached /backup/memcached.conf.$(date +%Y%m%d)

Performance Trending:
Maintain performance baselines and identify trends that may indicate capacity or configuration issues requiring attention.

Advanced Configuration

Advanced configurations enable specialized deployments and enhanced functionality for complex environments.

Multi-Instance Setup:
Run multiple Memcached instances on different ports:

sudo cp /etc/sysconfig/memcached /etc/sysconfig/memcached-2

Modify the second configuration file to use different ports and memory allocations, enabling service isolation and specialized caching strategies.

High Availability Considerations:
While Memcached doesn’t provide built-in clustering, implement application-level strategies for redundancy and failover capabilities.

Load Balancing Configuration:
Configure clients to distribute requests across multiple Memcached instances using consistent hashing algorithms for optimal load distribution.

Monitoring Integration:
Integrate Memcached with enterprise monitoring solutions like Nagios, Zabbix, or Prometheus for comprehensive infrastructure oversight.

Troubleshooting Guide

Effective troubleshooting resolves common issues quickly while preventing extended service disruptions.

Service Startup Failures:
Check service status and logs when Memcached fails to start:

sudo systemctl status memcached
sudo journalctl -u memcached --no-pager

Common causes include configuration errors, port conflicts, and insufficient permissions.

Connection Issues:
Diagnose connection problems using network testing tools:

sudo netstat -tulpn | grep 11211
sudo ss -tulpn | grep 11211

These commands verify that Memcached is listening on the expected port and interface.

Memory Allocation Errors:
Monitor system memory and adjust cache size if allocation fails:

free -h
echo "stats" | nc localhost 11211 | grep limit_maxbytes

Permission Problems:
Verify file and directory permissions for the memcached user:

sudo -u memcached ls -la /var/run/memcached/

Performance Degradation:
Investigate performance issues by analyzing cache statistics:

echo "stats" | nc localhost 11211 | grep -E "(evictions|reclaimed)"

High eviction rates may indicate insufficient cache memory or suboptimal expiration policies.

Best Practices and Security Recommendations

Implementing industry best practices ensures secure, reliable, and efficient Memcached operations in production environments.

Security Hardening Checklist:

  • Bind services to localhost unless network access is required
  • Implement firewall rules restricting access to authorized systems
  • Enable SASL authentication for network-accessible installations
  • Regular security updates and vulnerability assessments
  • Monitor access logs for suspicious connection patterns

Resource Allocation Guidelines:

  • Allocate 25-50% of system RAM for cache memory
  • Reserve adequate CPU resources for concurrent connection handling
  • Monitor disk I/O for configuration files and logs
  • Plan network bandwidth for peak cache traffic

Monitoring and Alerting Setup:
Implement comprehensive monitoring covering:

  • Service availability and response times
  • Memory utilization and eviction rates
  • Connection counts and error rates
  • System resource consumption

Regular Maintenance Schedules:
Establish consistent maintenance routines including configuration backups, performance reviews, and security updates to maintain optimal system health.

Congratulations! You have successfully installed Memcached. Thanks for using this tutorial for installing the Memcached open-source high-performance distributed memory caching on your Rocky Linux 10 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