Redis basics, persistence and security on a server
Redis is an in-memory key-value store that keeps data in RAM and saves it to disk with RDB snapshots, an append-only file or both, and it must be bound to localhost and password protected.
- Updated Nov 27, 2026
- Markdown
Run Redis safely with persistence, a password, a memory limit and an eviction policy that fits your use.
- An Ubuntu or Debian server with sudo, or Docker installed
Redis can save its memory to disk
- Writes land in memory first, and with RDB Redis saves a snapshot of the whole dataset to disk at set intervals.
- With AOF, every write command is appended to a log file.
- On restart, Redis replays the AOF to rebuild the data, and it prefers AOF when it is enabled.
- Without AOF, Redis loads the last RDB snapshot instead, and writes since then are lost.
Static diagram
- Redis memorysnapshotRDB snapshot
- Redis memoryappend writeAOF log
- AOF logreplay logRestart
- Restartdata backRedis memory
Redis keeps its data in memory and optionally saves it to disk, so you must choose how much loss you can accept and then secure it before anything else. Install it, check it with redis-cli ping, turn on persistence (RDB snapshots, an append-only file, or both), set a password, bind to localhost, and limit memory. Never expose port 6379 to the internet.
How it works#
Redis is a single-purpose server holding keys and values in RAM, which makes it very fast. Typical uses are caches, sessions, rate limit counters and job queues. Because the dataset lives in memory, two questions matter: what happens when the process stops, and what happens when memory runs out.
For the first question Redis has two persistence modes, and you can use both:
- RDB writes a compact point-in-time snapshot (
dump.rdb) when a rule such assave 3600 1 300 100 60 10000fires, and on shutdown. Restarts load it quickly. A crash loses writes since the last snapshot. - AOF (append-only file) logs each write command. With
appendfsync everysecthe file is flushed to disk once a second, so a crash loses about one second. The file grows, and Redis rewrites it in the background to keep it small.
With both on, Redis loads the AOF at start because it is the more complete record. For a pure cache you can turn persistence off entirely.
For the second question there is maxmemory and a policy. Without maxmemory, Redis keeps growing until the kernel’s out-of-memory killer steps in (see fix out-of-memory kills).
Step 1: Install and test#
sudo apt update
sudo apt install redis-server
sudo systemctl status redis-server
redis-cli pingThe reply PONG means the server answers. In Docker:
docker run -d --name redis \
-v redisdata:/data \
-p 127.0.0.1:6379:6379 \
redis:7 redis-server --appendonly yes --requirepass change-meThe image stores data in /data, so mount a named volume there. Replace change-me with a long random password. Binding the published port to 127.0.0.1 keeps it off the public interface, and the Docker publish lesson explains why this matters.
Step 2: Try the core commands#
SET greeting "hello"
GET greeting
EXPIRE greeting 60
TTL greeting
DEL greetingEXPIRE sets a time to live in seconds, and TTL shows what is left, -1 for no expiry and -2 for a missing key. SET greeting hello EX 60 sets the value and expiry together. For listing keys use SCAN 0 MATCH user:* COUNT 100 rather than KEYS *, which blocks the server on big datasets.
Step 3: Configure persistence#
The config file on Debian and Ubuntu is /etc/redis/redis.conf. Edit it with sudo and set:
appendonly yes
appendfsync everysec
save 3600 1 300 100 60 10000Then sudo systemctl restart redis-server. These three lines turn on both AOF and RDB. Check what the server uses with redis-cli CONFIG GET appendonly. Persistence files live in the directory set by dir, commonly /var/lib/redis. Back up that directory or copy dump.rdb while no rewrite is running, and test the restore as in test a backup by restoring it.
Step 4: Lock it down#
In redis.conf:
bind 127.0.0.1 -::1
protected-mode yes
requirepass change-mebind restricts the interfaces, protected-mode yes refuses outside clients when there is no password, and requirepass makes every client send AUTH. Use a long random value and keep it in an environment variable or secret. Redis 6 and later also has ACL users, which let you give each app its own account with limited commands:
ACL SETUSER worker on >change-me-too ~jobs:* +get +set +lpush +rpopThat user can act only on keys starting with jobs: and use four commands. Connect with redis-cli --user worker --pass change-me-too and see the URL forms in database connection strings explained. Block 6379 in your firewall from the internet, and do not rely on the password alone.
Step 5: Limit memory#
maxmemory 256mb
maxmemory-policy allkeys-lruPick the size from the RAM you can spare after your other services. The policies you will use most:
| Policy | Behavior when full |
|---|---|
noeviction | Writes fail with an error, reads continue. Right for queues and data you cannot lose. |
allkeys-lru | Evicts least recently used keys. Right for a cache. |
volatile-lru | Evicts only keys with an expiry. Keys with no TTL stay and can still fill memory. |
Watch usage with redis-cli INFO memory and look at used_memory_human and maxmemory_human.
Check it worked#
redis-cli pingreturnsPONG(add-aorAUTHfirst once a password is set).redis-cli CONFIG GET appendonlyreturnsyes.sudo ss -ltnp | grep 6379shows127.0.0.1:6379only, not0.0.0.0:6379.- From another machine,
nc -vz 203.0.113.10 6379fails. - After
SET k vand a restart of the service,GET kstill returnsv.
Edge cases and gotchas#
- FLUSHALL and FLUSHDB are destructive.
FLUSHALLdeletes every key in every database andFLUSHDBthe current one. With persistence on, the empty state is written to disk, so restarting does not bring the data back. Never run them on a server you have not confirmed, and consider disabling them for apps withrename-commandor ACL rules. - A password in the process list.
redis-cli -a change-mecan show up inpsand shell history. SetREDISCLI_AUTHor typeAUTHinside the session. - Memory spikes during saves. A background save forks the process, and heavy writes during it can raise memory use. Leave headroom beyond
maxmemory. - Disk-full persistence. If the disk fills, Redis may stop accepting writes with
MISCONF. - Docker without a volume. The container’s filesystem disappears with the container, so unmounted
/datameans lost snapshots. - Eviction is silent. With
allkeys-lru, important keys can be evicted. Use a separate instance for data you must keep.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
Could not connect to Redis at 127.0.0.1:6379: Connection refused | Server not running | sudo systemctl start redis-server and check logs |
(error) NOAUTH Authentication required. | requirepass set, no AUTH sent | AUTH change-me or use REDISCLI_AUTH |
(error) WRONGPASS invalid username-password pair or user is disabled. | Wrong password or ACL user | Check the password and ACL LIST |
(error) DENIED Redis is running in protected mode because protected mode is enabled and no password is set. | Remote client, no password | Set requirepass or connect locally |
(error) OOM command not allowed when used memory > 'maxmemory'. | noeviction and memory full | Raise maxmemory, or use an eviction policy for caches |
(error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. | Disk full or no write access to dir | Free space, fix permissions |
Can't handle RDB format version in the log | Dump from a newer Redis | Start a version at least as new |
(error) ERR unknown command for an ACL user | The user lacks that command | Add it with ACL SETUSER |
Quick reference#
# redis.conf
bind 127.0.0.1 -::1
protected-mode yes
requirepass change-me
appendonly yes
appendfsync everysec
save 3600 1 300 100 60 10000
maxmemory 256mb
maxmemory-policy allkeys-lruredis-cli ping
redis-cli INFO memory
redis-cli CONFIG GET appendonly
redis-cli SET k v EX 60Related lessons#
- Database connection strings explained: the redis:// and rediss:// URL forms.
- Publish container ports safely: keep Docker from exposing 6379.
- Set up a firewall with ufw: block the port from outside.
- Fix out-of-memory kills: what happens without maxmemory.
- Manage secrets for self-hosted Docker apps: store the Redis password properly.
Next#
Continue with database connection pooling and limits to stop apps from running a database out of connections.
Check what you learned
Frequently asked questions
What is the difference between RDB and AOF in Redis?
RDB saves point-in-time snapshots at intervals, which is compact and fast to load but can lose the writes since the last snapshot. AOF logs every write, so with appendfsync everysec you lose at most about a second.
Is Redis safe to expose to the internet?
No. Redis was designed for trusted networks, and an open instance is routinely taken over by scanners. Bind it to 127.0.0.1 or a private network, set a password, and block port 6379 in the firewall.
What does maxmemory-policy do?
When Redis reaches maxmemory, the policy decides what happens. noeviction rejects writes, allkeys-lru evicts the least recently used keys, and volatile-lru evicts only keys that have an expiry.
Does FLUSHALL delete data permanently?
Yes. It removes every key in every database, and with persistence on, the empty state is saved as well, so you cannot just restart to get the data back.
Sources
Keep going: guides and tutorials
- Self-Hosted Postgres in Docker: Connect It to Your App Run Postgres in Docker as its own resource with its own volume, connect your app with one command, and read the reachability badge before a timeout hits.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.