How to Install Redis on a VPS with Docker

Speed matters. Whether you’re building a real-time leaderboard, a session cache, or a job queue, slow data access kills the experience. Redis fixes that. It’s an in-memory data store that retrieves values in microseconds and has become the go-to caching layer for applications of every size.

Running Redis inside Docker on your VPS is the cleanest way to deploy it. You get easy upgrades, tidy isolation from the rest of your system and a reproducible setup you can version-control and replicate anywhere. This guide walks you through the entire process, from a bare VPS to a production-ready Redis instance sitting behind Nginx with SSL.

What Is Redis?

Redis stands for Remote Dictionary Server. Think of it as an enormous, lightning-fast dictionary living entirely in RAM. Every key maps to a value and every lookup happens in constant time. That’s the core promise.

But Redis is far more than a plain key-value store. It supports rich data structures out of the box.

  • Strings — counters, tokens, serialized objects
  • Lists — task queues, activity feeds
  • Sets and Sorted Sets — unique tags, ranked leaderboards
  • Hashes — user sessions, product catalogs
  • Streams — event logs, real-time messaging
  • Pub/Sub channels — live notifications, chat systems

Add optional persistence, replication and Lua scripting to the picture and you’ve got a tool that pulls triple duty as cache, message broker and lightweight database. It’s no accident that Redis consistently ranks among the most loved databases in developer surveys.

Prerequisites

Before touching a single command, confirm your VPS meets these requirements. Redis itself is lean but you’ll want breathing room for your application workloads too.

Requirement Minimum Recommended
CPU 1 vCPU 2 vCPUs
RAM 1 GB 2 GB or more
Disk 10 GB SSD 20 GB SSD
OS Ubuntu 22.04 LTS Ubuntu 24.04 LTS
Docker 24.x Latest stable
Docker Compose v2.x Latest stable
Open ports 80, 443 80, 443
Domain name Optional Required for SSL

You’ll also need a non-root user with sudo privileges and basic familiarity with the Linux command line. If Docker isn’t on your VPS yet, the first installation step covers that.

How to Install Redis on a VPS with Docker

Step 1: Update Your System

Start with a clean slate. Stale packages cause subtle, maddening conflicts later so deal with them now.

sudo apt update && sudo apt upgrade -y

Once the upgrade finishes, install a handful of utilities that Docker’s install script depends on.

sudo apt install -y ca-certificates curl gnupg lsb-release

Step 2: Install Docker and Docker Compose

Skip any distribution-packaged Docker. Those versions lag months behind and miss important security patches. Pull straight from Docker’s official repository instead.

Add Docker’s GPG key and repository.

sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg

echo /
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] /
  https://download.docker.com/linux/ubuntu /
  $(lsb_release -cs) stable" | /
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

Now install Docker Engine along with the Compose plugin.

sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Add your user to the docker group so you don’t need sudo for every Docker command.

sudo usermod -aG docker $USER
newgrp docker

Verify both tools are working.

docker --version
docker compose version

Step 3: Create the Project Directory Structure

Keeping everything under one parent directory makes backups, migrations and debugging far simpler. Create it now.

mkdir -p ~/redis-docker/{data,config,logs}
cd ~/redis-docker

The three subdirectories serve distinct purposes. data holds Redis’s persistence files (RDB snapshots and AOF logs). config stores the custom Redis configuration file. logs captures container output for later review.

Step 4: Create a Redis Configuration File

Redis ships with a solid set of defaults but a production deployment needs a few deliberate adjustments. Create the config file.

nano ~/redis-docker/config/redis.conf

Paste in this configuration. Each directive includes an inline comment explaining what it does and why it matters.

# Bind only to the loopback interface inside the container.
# Nginx handles all external traffic; Redis never speaks directly to the internet.
bind 127.0.0.1

# Require a strong password for every connection.
# Replace this value with a long random string — treat it like a root password.
requirepass YOUR_STRONG_PASSWORD_HERE

# Limit memory consumption. Adjust to roughly half your available VPS RAM.
maxmemory 512mb

# When memory fills up, evict the least-recently-used keys first.
# Keeps the cache fresh and prevents out-of-memory crashes.
maxmemory-policy allkeys-lru

# Enable AOF persistence so data survives container restarts.
appendonly yes
appendfilename "appendonly.aof"

# Sync the AOF to disk once per second — a good balance of safety and speed.
appendfsync everysec

# Also take an RDB snapshot periodically as a backup layer.
# Format: save <seconds> <changes>
save 3600 1
save 300 100
save 60 10000

# Log at the notice level — verbose enough to spot problems, quiet enough for production.
loglevel notice

# Send all logs to stdout so Docker can capture them with its logging driver.
logfile ""

# Disable protected mode since we're using requirepass for authentication.
protected-mode no

Save and exit the file. Remember to replace YOUR_STRONG_PASSWORD_HERE with an actual random password before moving on. A quick way to generate one:

openssl rand -base64 32

Step 5: Write the Docker Compose File

Docker Compose turns a multi-line docker run command into a readable, version-controlled declaration. Create it in the project root.

nano ~/redis-docker/docker-compose.yml
services:
  redis:
    image: redis:7-alpine
    container_name: redis
    restart: unless-stopped
    command: redis-server /usr/local/etc/redis/redis.conf
    ports:
      - "127.0.0.1:6379:6379"
    volumes:
      - ./config/redis.conf:/usr/local/etc/redis/redis.conf:ro
      - ./data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "YOUR_STRONG_PASSWORD_HERE", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    networks:
      - redis-net

networks:
  redis-net:
    driver: bridge

A few details worth calling out here. The port binding 127.0.0.1:6379:6379 keeps Redis off the public internet — only processes running on the same VPS can reach it directly. The redis:7-alpine image is the official Alpine-based variant, which clocks in under 30 MB and carries a minimal attack surface. The healthcheck ensures the container reports healthy only when Redis is actually accepting commands, not just when the process has started.

Update the healthcheck password to match what you put in redis.conf.

Step 6: Start the Redis Container

With the configuration in place, bring up the container.

cd ~/redis-docker
docker compose up -d

Docker pulls the image on first run, which takes a moment. Subsequent starts are instant. Check the container’s status once it’s up.

docker compose ps

You should see the container listed as running (healthy). If it shows starting wait ten seconds and run the command again — the healthcheck needs a moment to pass.

Verify Redis itself responds correctly.

docker exec -it redis redis-cli -a YOUR_STRONG_PASSWORD_HERE ping

Redis replies with PONG. That’s the confirmation you want.

Step 7: Install and Configure Nginx as a Reverse Proxy

Direct browser-based access to Redis doesn’t make much sense given its binary protocol but if you plan to expose a Redis web management UI (like RedisInsight) you need Nginx to front it properly. This step also positions you perfectly for SSL termination in the next step.

sudo apt install -y nginx

Create an Nginx server block for your domain. Replace redis.yourdomain.com with your actual domain or subdomain throughout this file.

sudo nano /etc/nginx/sites-available/redis
server {
    listen 80;
    server_name redis.yourdomain.com;

    location / {
        proxy_pass http://127.0.0.1:6379;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enable the site and restart Nginx.

sudo ln -s /etc/nginx/sites-available/redis /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Step 8: Secure the Connection with Let’s Encrypt SSL

Running anything over plain HTTP in 2024 is asking for trouble. Certbot issues a free, auto-renewing certificate in about sixty seconds.

sudo apt install -y certbot python3-certbot-nginx

Point your domain’s DNS A record at your VPS IP address and then request the certificate. Certbot modifies your Nginx config automatically to handle the HTTPS redirect.

sudo certbot --nginx -d redis.yourdomain.com

Follow the prompts, provide an email address for renewal notices and accept the terms. Certbot finishes by reloading Nginx. Test that auto-renewal works correctly.

sudo certbot renew --dry-run

A successful dry run means your certificate will renew without intervention. Certbot registers a systemd timer that handles this automatically every 12 hours.

Step 9: Test Redis with Some Real Commands

A working Redis deployment deserves a proper smoke test. Jump into the container’s interactive CLI and run through the core data types.

docker exec -it redis redis-cli -a YOUR_STRONG_PASSWORD_HERE

Try a few commands to confirm everything behaves as expected.

# Store and retrieve a simple string
SET greeting "Hello from Redis"
GET greeting

# Set a key that expires after 60 seconds
SET session:abc123 "user_data" EX 60
TTL session:abc123

# Work with a list
RPUSH tasks "send_email" "resize_image" "sync_inventory"
LRANGE tasks 0 -1

# Increment a counter atomically
SET page_views 0
INCR page_views
INCR page_views
GET page_views

# Check memory usage
INFO memory

# Exit the CLI
QUIT

If every command returns the expected value your installation is solid. The INFO memory command is particularly useful — it shows how much RAM Redis is actually consuming versus your configured maxmemory limit.

Connecting Your Application to Redis

A Redis instance with no clients is like a sports car in a garage. Here’s how to connect from the most common application environments. In each case Redis lives at 127.0.0.1:6379 on the same VPS.

Node.js (ioredis)

const Redis = require('ioredis');

const redis = new Redis({
  host: '127.0.0.1',
  port: 6379,
  password: 'YOUR_STRONG_PASSWORD_HERE',
});

async function demo() {
  await redis.set('framework', 'Express');
  const value = await redis.get('framework');
  console.log(value); // Express
}

demo();

Python (redis-py)

import redis

r = redis.Redis(
    host='127.0.0.1',
    port=6379,
    password='YOUR_STRONG_PASSWORD_HERE',
    decode_responses=True
)

r.set('language', 'Python')
print(r.get('language'))  # Python

PHP (Predis)

require 'vendor/autoload.php';

$client = new Predis/Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
    'port'   => 6379,
    'password' => 'YOUR_STRONG_PASSWORD_HERE',
]);

$client->set('cms', 'WordPress');
echo $client->get('cms'); // WordPress

How to Update Redis

Docker makes version upgrades nearly painless. The whole process takes under two minutes and your data survives untouched because it lives in the mounted ./data volume.

Pull the latest image for your chosen tag.

cd ~/redis-docker
docker compose pull

Restart the container with the new image.

docker compose up -d

Confirm the running version.

docker exec -it redis redis-cli -a YOUR_STRONG_PASSWORD_HERE info server | grep redis_version

Clean up the old image layer to reclaim disk space.

docker image prune -f

For major version jumps (say, Redis 7 to Redis 8 when it lands) check the official release notes first. Breaking changes are rare but they do happen between major versions.

Troubleshooting

Container Exits Immediately on Start

If the container spins up and then stops within seconds the config file is the most likely culprit. Redis exits with a non-zero code when it encounters a directive it doesn’t recognize.

Check the logs immediately after the crash.

docker compose logs redis

Look for a line starting with # Fatal error or ** FATAL CONFIG FILE ERROR. The line below it names the specific directive causing the problem. Fix the typo or remove the unsupported option and restart.

docker compose up -d

Authentication Error: NOAUTH or WRONGPASS

These errors mean the password in your connection string doesn’t match the requirepass value in redis.conf. They’re easy to get out of sync, especially during config edits.

Open redis.conf and confirm the password, then test the connection directly from the container.

docker exec -it redis redis-cli -a THE_PASSWORD_FROM_CONFIG ping

If that succeeds, the issue is in your application’s connection config, not in Redis itself. Update the password string in your app and reconnect.

Redis Is Using Too Much Memory

Left unchecked Redis will consume all available RAM if keys never expire and no maxmemory limit is set. The maxmemory directive in your config prevents this but you might find it needs tuning over time.

Check the current memory picture.

docker exec -it redis redis-cli -a YOUR_STRONG_PASSWORD_HERE info memory

The used_memory_human line shows actual consumption. If it’s close to your maxmemory limit consider either raising the limit or reviewing which keys hold the most data.

# Find the largest keys in your database
docker exec -it redis redis-cli -a YOUR_STRONG_PASSWORD_HERE --bigkeys

Data Disappears After Container Restart

If keys vanish every time you restart the container your persistence configuration isn’t working as intended. Two things to verify: the ./data volume is correctly mounted and appendonly yes is present in your config.

Inspect the volume mount.

docker inspect redis | grep -A 10 Mounts

You should see your local data directory mapped to /data inside the container. If the mount is missing the volume path in docker-compose.yml has a typo. Also confirm the AOF file actually exists on disk.

ls -lh ~/redis-docker/data/

You should see an appendonly.aof file there. If it’s absent Redis either isn’t writing persistence to the mounted volume or appendonly is still disabled in the config.

Can’t Connect from an External Application on Another Server

This is intentional behavior by design. The port binding 127.0.0.1:6379:6379 limits Redis to localhost-only connections. If a separate application server needs to reach Redis the cleanest solution is an encrypted SSH tunnel.

From the application server, open the tunnel.

ssh -L 6379:127.0.0.1:6379 user@your-vps-ip -N -f

Your application can now connect to 127.0.0.1:6379 locally and all traffic flows through the encrypted SSH tunnel to your VPS. Never bind Redis to 0.0.0.0 to solve this problem — that exposes port 6379 to the entire internet, which is a serious security risk regardless of your firewall rules.

What to Do Next

A running Redis instance is a solid foundation but there’s plenty more to explore depending on your use case.

  • Add Redis Sentinel for automatic failover if high availability matters to your workload
  • Deploy RedisInsight, the official browser-based GUI, to visualize keys, run queries and monitor performance without touching the CLI
  • Configure ACLs (Access Control Lists) to restrict what specific users and applications can read or write
  • Integrate with your framework’s cache layer — Laravel, Django and Rails all have first-class Redis adapters that plug in with minimal configuration
  • Set up log rotation with logrotate to keep the logs directory from growing unbounded over time

Redis rewards experimentation. The more you push it, the more you discover just how versatile a tool it really is.

Closing Thoughts

You now have a production-grade Redis deployment running in Docker on your VPS, secured with a strong password, persistence enabled and Nginx standing guard at the door. The entire stack sits cleanly inside a single project directory and you can replicate it on a new server in minutes by copying three files.

That’s the real advantage of the Docker approach. The environment travels with you. Upgrade, migrate, clone — the process is the same every time. And with GreenGeeks VPS hosting under it all you get NVMe SSD storage and optimized networking that let Redis do what it does best: answer fast.

The post How to Install Redis on a VPS with Docker appeared first on GreenGeeks.

版权声明:
作者:感冒的梵高
链接:https://www.techfm.club/p/236960.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>