Install Redis Cache on Ubuntu VPS

Redis is an in-memory data store that keeps data in RAM, making reads hundreds of times faster than MySQL or disk-based storage. It's ideal for session caching, object caching, job queues, and rate limiting. This guide walks through installing Redis on Ubuntu VPS and connecting it to PHP and WordPress.

System Requirements

Step 1: Install Redis

Update the package list and install Redis:

apt update && apt install redis-server -y

Verify Redis is running:

systemctl status redis-server

Run a quick connectivity test:

redis-cli ping

If you get PONG, Redis is up and running.

Step 2: Configure Redis

Edit the main config file:

nano /etc/redis/redis.conf

Limit Memory Usage

Find # maxmemory and set it to about 25% of your total RAM:

maxmemory 256mb maxmemory-policy allkeys-lru

Bind to Localhost Only

Make sure the bind line reads:

bind 127.0.0.1 -::1

Enable Persistent Storage (Recommended)

Let Redis save snapshots to disk so data survives a reboot:

save 900 1 save 300 10 save 60 10000

Reload the configuration:

systemctl restart redis-server systemctl enable redis-server

allkeys-lru means Redis will evict the least recently used keys when memory is full — the right policy for a general-purpose cache.

Step 3: Use Redis with PHP

Install the PHP Redis extension:

apt install php-redis -y systemctl restart php8.2-fpm # adjust to your PHP version

Test from a PHP script:

<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // Store a value $redis->set('test_key', 'Hello Redis!', 60); // expires in 60 seconds // Retrieve it echo $redis->get('test_key'); // Hello Redis! ?>

Step 4: Use Redis with WordPress

Redis dramatically speeds up WordPress by caching database query results in memory instead of hitting MySQL on every request.

Install the Plugin

Install the Redis Object Cache plugin from the WordPress Repository, then go to Settings → Redis Object Cache → Enable Object Cache.

Or Configure in wp-config.php

define('WP_REDIS_HOST', '127.0.0.1'); define('WP_REDIS_PORT', 6379); define('WP_CACHE', true);

Real-world impact: WordPress sites with Redis Object Cache typically see a 30–60% reduction in response time because repeated DB queries are served from RAM instead of disk.

Step 5: Monitor and Flush Cache

Live Command Monitor

redis-cli monitor # watch all commands in real time redis-cli info stats # hit/miss ratio redis-cli info memory # RAM usage breakdown

Check Hit Rate

redis-cli info stats | grep -E "keyspace_hits|keyspace_misses"

A healthy cache hit rate is above 80%. If it's lower, increase maxmemory to allow more data to stay cached.

Flush All Cache

redis-cli flushall

Install Redis on a VPS the Production Way

In a real production environment on a VPS, you should set things up more carefully than a bare apt install — verifying the version, confirming the service user, and enabling the systemd unit so Redis restarts automatically after a reboot. The steps below were tested on Ubuntu 22.04 LTS running on an AsiaGB VPS (from ฿500/month), which provides full root access so every command runs without restriction.

First, update the system and install Redis along with the tools you need:

apt update && apt upgrade -y
apt install redis-server redis-tools -y
redis-server --version
redis-cli --version

Confirm Redis is running and enable it to start automatically when the VPS reboots:

systemctl enable --now redis-server
systemctl status redis-server --no-pager
redis-cli ping        # should return PONG

On Ubuntu, Redis already runs as the dedicated redis user under systemd. Verify it with:

ps -u redis -o pid,cmd
ss -tlnp | grep 6379    # must bind to 127.0.0.1:6379 only

If ss shows Redis listening on 0.0.0.0:6379 (all interfaces), it is exposed to the public internet and must be fixed immediately in the security section below. A public, password-less Redis is one of the most frequently scanned and exploited misconfigurations on any VPS.

Use Redis as a Cache for WordPress and Laravel

The clearest benefit of running Redis on a VPS is using it as an object cache and session store for both WordPress and Laravel. By moving load off MySQL and the filesystem into RAM, each request responds far faster — especially on sites with many plugins or complex queries.

WordPress — Object Cache

After installing the Redis Object Cache plugin, add these values to wp-config.php to keep each site's cache isolated (critical if one Redis instance serves multiple sites):

define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);
define('WP_CACHE_KEY_SALT', 'mysite_');  // prefix to avoid key collisions
define('WP_REDIS_MAXTTL', 86400);
define('WP_CACHE', true);

Then go to Settings → Redis and click Enable Object Cache. Once connected you'll see a Connected status, and the hit rate climbs as traffic flows through the cache.

Laravel — Cache and Session

Laravel supports Redis natively via the predis/predis package or the PhpRedis extension. Configure it in .env:

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=your_chosen_password
REDIS_PORT=6379

Example of caching a heavy query result for 10 minutes in Laravel:

use Illuminate\Support\Facades\Cache;

$users = Cache::remember('active_users', 600, function () {
    return User::where('active', 1)->get();
});

Moving sessions onto Redis also makes scaling easier, since sessions are no longer tied to files on a single machine — ideal for sites with many concurrent users.

Tip: Use a different WP_REDIS_DATABASE or REDIS_DB number (0–15) to separate the cache of each app or site on a single Redis instance. You can then flush one site without affecting the others.

Secure Redis (bind, requirepass, protected-mode)

Redis is designed to run inside a trusted internal network, so its defaults don't prioritise security. On a VPS with a public IP you must close off all external access — otherwise bots scanning port 6379 can take over the machine for crypto mining or a botnet within minutes.

1. Bind to localhost and enable protected-mode

Edit /etc/redis/redis.conf and make sure these values are set:

bind 127.0.0.1 -::1
protected-mode yes
port 6379

protected-mode yes automatically rejects external connections that have no password — your first line of defence.

2. Set a password with requirepass

Generate a long, random password and add it to the config file:

# generate a random 32-byte password
openssl rand -base64 32

# in /etc/redis/redis.conf add:
requirepass your_long_random_password_here

After setting a password, connections must authenticate before issuing commands:

redis-cli
127.0.0.1:6379> AUTH your_long_random_password_here
OK

3. Disable or rename dangerous commands

Commands like FLUSHALL, CONFIG, and KEYS can wipe data or cause a DoS. Disable or rename them in the config:

rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_a8f3k2"

4. Add a firewall layer

Block port 6379 from the outside with UFW for extra assurance:

ufw deny 6379
ufw reload

After all changes, restart to apply them:

systemctl restart redis-server

Warning: Never set bind 0.0.0.0 on a VPS with a public IP. If an app on another machine needs to reach Redis, use an SSH tunnel or a private network inside the datacenter rather than exposing the port to the internet.

Configure maxmemory, Eviction Policy and Monitoring

RAM on a VPS is finite, so capping Redis to keep it from consuming all memory and triggering the OOM killer is essential. Use maxmemory to set the ceiling and maxmemory-policy to decide what happens when it fills up.

Pick the right eviction policy

Policy Behaviour when RAM is full Best for
allkeys-lru Evicts least recently used keys General cache, WordPress
allkeys-lfu Evicts least frequently used keys Caches with clear hot keys
volatile-lru Evicts only keys with a TTL Mixed cache + persistent data
noeviction Rejects new writes (error) Using Redis as a real database

Recommended values for a 2 GB RAM VPS (allocating ~512 MB to Redis):

maxmemory 512mb
maxmemory-policy allkeys-lru
maxmemory-samples 5

Monitor real-world usage

Keep an eye on Redis health regularly with these commands:

redis-cli info memory | grep used_memory_human
redis-cli info stats | grep -E "keyspace_hits|keyspace_misses|evicted_keys"
redis-cli --stat        # live figures every second
redis-cli dbsize        # total number of keys

Compute the hit rate as hits / (hits + misses) — it should stay above 80%. If evicted_keys keeps climbing, RAM is too tight; raise maxmemory or upgrade your VPS plan to one with more RAM.

Important: Don't set maxmemory close to the VPS's total RAM, because the OS and other services (PHP-FPM, MySQL, Nginx) also need memory. As a rule of thumb, keep Redis under 25–40% of total RAM.

Frequently Asked Questions (FAQ)

How is Redis different from Memcached?

Both are in-memory caches, but Redis supports richer data structures (lists, hashes, sets, sorted sets), can persist to disk, and offers Pub/Sub and replication. Memcached is simpler and lighter for pure key-value caching. For most VPS workloads, Redis is more capable and flexible.

How much RAM does a VPS need to run Redis?

Redis can start with just a few tens of MB, but in practice you want at least 1 GB so there's room for the OS, web server, and Redis's own cache. AsiaGB VPS starts at ฿500/month on Ubuntu and comfortably runs Redis.

Does Redis data survive a VPS reboot?

It depends on your persistence settings. With RDB snapshots (the save directives) or AOF enabled, Redis restores data after a reboot. If you use it purely as a cache, lost data isn't a problem — the system simply rebuilds the cache from the primary source (MySQL) automatically.

Why is my Redis hit rate low?

Common causes are a maxmemory that's too small (keys get evicted quickly), TTLs that are too short, or inconsistent cache keys in the application. Increasing maxmemory, checking evicted_keys, and reviewing your TTLs usually improves the hit rate noticeably.

Summary

Need a VPS for Redis?

AsiaGB Linux VPS starts at ฿500/month · Full Root Access · SSD Storage · Unlimited Bandwidth · Choose any Ubuntu version

View VPS Plans

View all affordable VPS Thailand plans →