Redis exposed to the internet: how to bind it to localhost and set a password
Redis has no login by default and was designed for trusted networks. A Redis reachable from the internet is routinely found and abused to store malware, run commands or steal data.
Check how it is listening
127.0.0.1 is safe. 0.0.0.0 or your public address is not.
sudo ss -ltnp | grep 6379 redis-cli CONFIG GET bindBind to localhost and keep protected mode
Edit the configuration file, not CONFIG SET, so it survives a restart.
sudo sed -i 's/^bind .*/bind 127.0.0.1 ::1/; s/^protected-mode .*/protected-mode yes/' /etc/redis/redis.conf grep -E '^(bind|protected-mode)' /etc/redis/redis.confRequire authentication
Even on localhost, a password stops other users and compromised apps on the machine. Use a long random value and put the same one in your application.
openssl rand -base64 32 echo 'requirepass THE_PASSWORD' | sudo tee -a /etc/redis/redis.confRestart and test
The restart briefly empties a cache that has no persistence.
sudo systemctl restart redis-server redis-cli ping # NOAUTH Authentication required redis-cli -a THE_PASSWORD ping # PONGTest from outside and close the port
From another machine, the port must be closed or filtered. Block it in the firewall as well.
nmap -Pn -p 6379 SERVER_IP sudo ufw deny 6379
Common mistakes
- Setting bind 0.0.0.0 because an app on another server needs it: use a private network or an SSH tunnel instead.
- Containers published with -p 6379:6379, which bypass UFW.
- Putting the password on the command line where it shows in the process list.
How to undo it
Restore the previous /etc/redis/redis.conf from your backup and restart redis-server.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.