MySQL and MariaDB Installation: Basic Management Guide
Step-by-step MySQL and MariaDB installation on Linux, mysql_secure_installation, creating databases and users, basic SQL commands, remote access configuration, and performance tuning.
Redis and Memcached installation on Ubuntu/Debian, basic commands, persistence settings, TTL configuration, Redis vs Memcached comparison, and application integration.
A cache layer is a critical infrastructure component that dramatically improves web application performance. By storing database queries, API responses, and computation results in memory, it enables millisecond responses to repeated requests. This guide covers the installation, configuration, and application integration of Redis and Memcached — the two most widely used cache systems.
Both systems offer high-performance in-memory data storage, but they target different use cases:
| Feature | Redis | Memcached |
|---|---|---|
| Data structures | String, Hash, List, Set, ZSet | String only |
| Persistence | RDB + AOF | None |
| Replication | Master-Replica + Cluster | None |
| Pub/Sub | Yes | No |
| Lua scripting | Yes | No |
| Multi-threading | Partial (I/O) | Full |
| Memory efficiency | Medium | High |
Redis is recommended for new projects. With rich data structures, persistence, and replication support, it covers far more use cases. Memcached is preferred only when you need simple string caching and maximum multi-threaded performance.
# Update package list
apt update
# Install Redis
apt install -y redis-server
# Check service status
systemctl status redis-server
# Enable auto-start
systemctl enable redis-server
# Install required tools
apt install -y curl gpg
# Add Redis GPG key
curl -fsSL https://packages.redis.io/gpg | gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
# Add repository
echo 'deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb '$(lsb_release -cs)' main' | tee /etc/apt/sources.list.d/redis.list
# Update and install
apt update
apt install -y redis
redis-server --version
# Output: Redis server v=7.x.x ...
redis-cli --version
# Output: redis-cli 7.x.x
# Enable EPEL repository
dnf install -y epel-release
# Install Redis
dnf install -y redis
# Start and enable service
systemctl start redis
systemctl enable redis
# Check status
systemctl status redis
# Edit configuration file
nano /etc/redis/redis.conf
# Listening address (localhost only)
bind 127.0.0.1
# Port (default 6379)
port 6379
# Password protection
requirepass StrongRedisPassword123!
# Maximum memory usage
maxmemory 512mb
# Eviction policy when memory is full
maxmemory-policy allkeys-lru
# Run as daemon
daemonize yes
# Log file
logfile /var/log/redis/redis-server.log
# Number of databases
databases 16
systemctl restart redis-server
# Verify configuration
redis-cli -a StrongRedisPassword123! ping
# Output: PONG
# Connect to Redis CLI
redis-cli
# Connect with password
redis-cli -a StrongRedisPassword123!
# Connect to remote server
redis-cli -h 192.168.1.100 -p 6379 -a password
# Connection test
PING
# Response: PONG
# Set a string value
SET user:1:name 'John Doe'
# Read value
GET user:1:name
# Set value with TTL (in seconds)
SETEX session:abc123 3600 'user_data'
# Check remaining time
TTL session:abc123
# Delete value
DEL user:1:name
# Check if key exists
EXISTS user:1:name
# List all keys (use carefully in production)
KEYS *
# Search with pattern
KEYS user:*
# Set hash
HSET user:1 name 'John' email 'john@example.com' age 30
# Read hash field
HGET user:1 name
# Read all hash fields
HGETALL user:1
# Delete hash field
HDEL user:1 age
# Check if hash field exists
HEXISTS user:1 email
# Add element to list (left)
LPUSH tasks 'task1' 'task2'
# Add element to list (right)
RPUSH tasks 'task3'
# Get element from list (left)
LPOP tasks
# List length
LLEN tasks
# List range
LRANGE tasks 0 -1
# Add element to set
SADD tags 'redis' 'cache' 'nosql'
# List set members
SMEMBERS tags
# Add to sorted set with score
ZADD leaderboard 1500 'player1' 2300 'player2' 800 'player3'
# List sorted (ascending)
ZRANGE leaderboard 0 -1 WITHSCORES
# List sorted (descending)
ZREVRANGE leaderboard 0 2 WITHSCORES
RDB writes a snapshot of the entire dataset to disk at specified intervals:
# /etc/redis/redis.conf
# Save if 1 change in 900 seconds
save 900 1
# Save if 10 changes in 300 seconds
save 300 10
# Save if 10000 changes in 60 seconds
save 60 10000
# RDB filename
dbfilename dump.rdb
# RDB directory
dir /var/lib/redis
AOF appends every write operation to a log file, providing more reliable persistence:
# Enable AOF
appendonlyfile yes
# AOF filename
appendfilename 'appendonly.aof'
# Sync policy
# always: On every write (safest, slowest)
# everysec: Every second (recommended)
# no: Leave to OS (fastest, least safe)
appendsync everysec
# AOF rewrite threshold
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
Using both RDB and AOF in production is recommended. RDB provides fast restarts, while AOF minimizes data loss.
# Update package list
apt update
# Install Memcached
apt install -y memcached libmemcached-tools
# Check service status
systemctl status memcached
# Enable auto-start
systemctl enable memcached
# Install Memcached
dnf install -y memcached
# Start and enable service
systemctl start memcached
systemctl enable memcached
# Edit configuration file
nano /etc/memcached.conf
# Memory limit (MB)
-m 256
# Listening address
-l 127.0.0.1
# Port
-p 11211
# Maximum connections
-c 1024
# Thread count (based on CPU cores)
-t 4
# Maximum object size (bytes)
-I 1m
# Restart service
systemctl restart memcached
# Test connection
echo 'stats' | nc 127.0.0.1 11211
# Connect via telnet
telnet 127.0.0.1 11211
# Set value (key, flag, TTL seconds, size bytes)
set session:xyz 0 3600 12
user_data
# Get value
get session:xyz
# Delete value
delete session:xyz
# View statistics
stats
# Clear all data
flush_all
# Install PHP Redis extension
apt install -y php-redis
systemctl restart php8.x-fpm
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('StrongRedisPassword123!');
// Write to cache
$redis->setex('user:1', 3600, json_encode(['name' => 'John', 'email' => 'john@example.com']));
// Read from cache
$data = $redis->get('user:1');
if ($data) {
$user = json_decode($data, true);
} else {
// Fetch from database and cache
$user = fetch_from_database(1);
$redis->setex('user:1', 3600, json_encode($user));
}
# Install ioredis package
npm install ioredis
const Redis = require('ioredis');
const redis = new Redis({
host: '127.0.0.1',
port: 6379,
password: 'StrongRedisPassword123!'
});
// Write to cache
await redis.setex('product:42', 1800, JSON.stringify({ name: 'Laptop', price: 999 }));
// Read from cache
const data = await redis.get('product:42');
if (data) {
const product = JSON.parse(data);
console.log(product);
}
// Clear cache
await redis.del('product:42');
# Install redis-py package
pip install redis
import redis
import json
r = redis.Redis(
host='127.0.0.1',
port=6379,
password='StrongRedisPassword123!',
decode_responses=True
)
# Write to cache
r.setex('article:5', 7200, json.dumps({'title': 'Redis Guide', 'content': '...'}))
# Read from cache
data = r.get('article:5')
if data:
article = json.loads(data)
# Redis service management
systemctl start redis-server
systemctl stop redis-server
systemctl restart redis-server
systemctl status redis-server
# View Redis logs
journalctl -u redis-server -f
tail -f /var/log/redis/redis-server.log
# Get Redis info via CLI
redis-cli INFO server
redis-cli INFO memory
redis-cli INFO stats
# Memcached service management
systemctl start memcached
systemctl stop memcached
systemctl restart memcached
systemctl status memcached
Redis and Memcached are powerful cache solutions that significantly improve application performance. Redis's rich data structures and persistence features make it ideal for most scenarios, while Memcached can be preferred for simple, high-performance string caching needs. Both systems run smoothly on REXE servers.
Redis is recommended for new projects. It offers rich data structures beyond strings — Hash, List, Set, Sorted Set; provides persistence with RDB and AOF; supports Pub/Sub messaging and Lua scripting. Memcached is preferred only for simple string caching and maximum multi-threaded performance. For most web applications, Redis is the better choice.
The most common policies: allkeys-lru (evict least recently used among all keys — recommended for general cache), volatile-lru (LRU among TTL-only keys — for mixed use), allkeys-lfu (evict least frequently used — for repetitive access patterns), noeviction (return error when memory is full — for critical data). For general cache use, allkeys-lru is the safest choice.
Using both together is the best approach. RDB takes periodic snapshots and provides fast restarts, but data since the last snapshot may be lost. AOF logs every write operation and minimizes data loss but uses more disk I/O. In production, enable both: RDB with save directives and AOF with appendonlyfile yes.
In redis.conf, change bind 127.0.0.1 to bind 0.0.0.0 and set a strong password with requirepass. Then open port 6379 in the firewall: ufw allow 6379/tcp. For security, rather than exposing Redis directly to the internet, use SSH tunneling or VPN. If possible, restrict access to specific IP addresses.
No, Memcached is a purely in-memory system with no persistence support. All data is lost when the server restarts. Therefore, Memcached should only be used for temporary cache data that can be regenerated. For persistent data storage or session management, use Redis instead.
Use redis-cli INFO memory to see detailed memory statistics. Pay attention to used_memory (memory in use), maxmemory (maximum limit), and mem_fragmentation_ratio (fragmentation ratio). If the fragmentation ratio exceeds 1.5, you can optimize memory with the MEMORY PURGE command. You can also monitor real-time statistics with redis-cli --stat.
Step-by-step MySQL and MariaDB installation on Linux, mysql_secure_installation, creating databases and users, basic SQL commands, remote access configuration, and performance tuning.
PostgreSQL installation on Ubuntu/Debian and RHEL/CentOS, creating users and databases, basic SQL commands, remote connection setup, and backup strategies. Step-by-step guide.
Step-by-step phpMyAdmin installation on Apache and Nginx, SSL configuration, user management, IP restrictions, and security hardening best practices.