How to Install and Optimize Redis Server on Ubuntu 24.04: In-Memory Cache and Security

Ubuntu tutorial - IT technology blog
Ubuntu tutorial - IT technology blog

When traffic hits tens of thousands of requests per minute, relational databases such as PostgreSQL or MySQL are often the first bottleneck. Complex JOIN queries can take anywhere from 50ms to 200ms to respond. Introducing an in-memory caching layer between your application and database solves this problem. With read and write latencies typically between 0.5ms and 2ms, Redis is the most popular choice today.

Comparing Redis Deployment Options on Ubuntu

Before diving into configuration, you should choose the deployment method that best fits your infrastructure. On Ubuntu 24.04 LTS (Noble Numbat), there are three common approaches:

  • Native APT Installation (Native Service): Uses the official package from Redis Labs, managing the process via systemd.
  • Running via Docker Container: Packages Redis as an isolated service managed via Docker Engine or Docker Compose.
  • Compiling from Source (Build from source): Downloads the tarball from the official site and compiles it using gcc and make.

Evaluating the Pros and Cons of Each Method

Below is a detailed comparison of the three deployment strategies:

Criteria Native APT (Recommended) Docker Container Compile from Source
Performance & Resources Maximum. Zero RAM overhead from a container engine; direct memory bus I/O. Bridge network latency is 5-10% higher than native unless configured with host network. Highest performance due to the ability to enable compiler optimization flags specific to your CPU architecture.
Maintenance & Updates Effortless. Upgrade versions with a single apt upgrade redis-server command. Requires tracking image tags, data volumes, and managing the Docker daemon itself. Complex. Every patch requires downloading new source code, rebuilding, and reconfiguring manually.
Process Management Native, deep integration with systemd and journald. Dependent on the restart policy of the Docker daemon. Requires writing a custom redis.service unit file from scratch.

Which Method Should You Choose for Your Server?

If your system runs on a distributed microservices architecture on Kubernetes, Docker is clearly the more convenient choice. Conversely, if you operate a VPS running a monolithic application (Laravel, Node.js, Django) or are building a dedicated cache server, choose Native APT.

This approach allows you to make full use of your server’s RAM. You avoid the 150-200MB overhead of the Docker daemon, and monitoring the service via systemctl is significantly more straightforward.

Steps to Install and Configure Redis on Ubuntu 24.04

Below is a 6-step walkthrough to set up a secure, production-ready Redis Server.

Step 1: Install Redis from the Official Redis.io Repository

The default Ubuntu 24.04 repositories are often frozen on older releases. To receive the latest bug fixes and improvements, install packages directly from the official Redis.io repository:

# Install repository download and verification tools
sudo apt update
sudo apt install -y lsb-release curl gpg

# Download and add Redis GPG key to system
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

# Add official Redis repository
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

# Update package list and install
sudo apt update
sudo apt install -y redis-server

Step 2: Configure RAM Limits and Eviction Policy

By default, Redis does not limit its memory usage. When memory is exhausted, the Linux OOM (Out-Of-Memory) Killer will terminate the heaviest processes on the server—typically MySQL or Redis itself.

Open the configuration file:

sudo nano /etc/redis/redis.conf

Locate and configure the following two directives (for example, allocating 2GB of RAM on a 4GB VPS):

# Maximum RAM limit for Redis
maxmemory 2gb

# Eviction policy when reaching memory limit
maxmemory-policy allkeys-lru

If you use Redis purely as a cache, allkeys-lru is the best choice. This algorithm evicts the least recently used keys to make room for new ones. If you also store user sessions or login tokens (which should not be evicted prematurely), switch to volatile-lru to evict only keys that have an expiration (TTL) set.

Step 3: Tighten Access Port Security

Botnets like Kinsing and Redigo constantly scan port 6379 across the Internet seeking exposed Redis instances to compromise root servers. The following two settings are mandatory:

  1. Listen on Localhost (or Private Internal IP) Only:

    Check the bind directive in /etc/redis/redis.conf to ensure Redis is not listening on 0.0.0.0:

    bind 127.0.0.1 -::1
    protected-mode yes
    
  2. Set an Authentication Password (Requirepass):

    Uncomment the requirepass line and set a strong, random password with at least 30 characters:

    requirepass c8F29aKx91LmP30qWs7TvYbRtU4VnZ5e!
    

Step 4: Tune the Linux Kernel for Redis

When Redis saves a background snapshot to disk via fork(), the child process requires virtual memory equivalent to the parent process. If free RAM is insufficient, this allocation fails. Enable vm.overcommit_memory = 1 to resolve log warnings:

# Apply immediately to running kernel
sudo sysctl vm.overcommit_memory=1

# Persist in configuration file across server reboots
echo 'vm.overcommit_memory = 1' | sudo tee -a /etc/sysctl.conf

Step 5: Apply Changes and Enable Service on System Boot

After modifying the configuration file, restart the process for the new settings to take effect:

# Restart Redis service
sudo systemctl restart redis-server

# Enable service on system boot
sudo systemctl enable redis-server

# Check status
sudo systemctl status redis-server

When the screen displays Active: active (running) in green along with the uptime, the service is running properly.

Step 6: Verify Connectivity and Security with Redis CLI

Open your terminal and verify the CLI response to ensure password authentication is active:

redis-cli

Test access authorization and sample data storage:

# Ping command before authentication
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.

# Authenticate with newly set password
127.0.0.1:6379> auth c8F29aKx91LmP30qWs7TvYbRtU4VnZ5e!
OK

# Test writing and reading a key
127.0.0.1:6379> set user:1001 "Nguyen Van A"
OK
127.0.0.1:6379> get user:1001
"Nguyen Van A"

# Exit redis-cli
127.0.0.1:6379> exit

Troubleshooting Common Issues

If the restart command throws an error, avoid guessing the cause. Open real-time systemd logs to read detailed messages:

sudo journalctl -u redis-server -e --no-pager

The most common issues include:

  • Syntax errors or incorrect whitespace in /etc/redis/redis.conf.
  • Port 6379 is already occupied by another process (or an existing Redis container).
  • Ownership permissions of the /var/lib/redis data directory were changed to root instead of the redis user.

By following the steps above, you will have a solid Redis Server setup: running smoothly, freeing RAM safely, and well-shielded against automated port scanning.

Share: