What's Actually Happening

Your application cannot connect to Redis, receiving connection refused errors. The Redis client fails to establish a connection, preventing caching, session storage, or message queue functionality from working. Applications may show errors indicating that Redis is unreachable, connection timed out, or connection refused.

This occurs when Redis server is not running, is listening on wrong interface/port, firewall blocks access, Redis requires authentication, or network configuration prevents the connection. The impact ranges from slow performance (missing cache) to complete application failure.

The Error You'll See

``` # Connection refused errors Redis::CannotConnectError: Could not connect to Redis at 127.0.0.1:6379: Connection refused

redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.

ERR Client sent AUTH, but no password is set

NOAUTH Authentication required

Could not connect to Redis at 127.0.0.1:6379: Connection refused

redis-cli: Could not connect to Redis at 127.0.0.1:6379: Connection refused

# Timeout errors Redis::TimeoutError: Connection timed out

# Application errors Error: Redis connection failed - ECONNREFUSED 127.0.0.1:6379

# Laravel/PHP Predis\Connection\ConnectionException : Connection refused [tcp://127.0.0.1:6379]

# Node.js Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 ```

Why This Happens

  1. 1.Redis server not running: The Redis service is stopped, crashed, or failed to start.
  2. 2.Wrong host or port: Application configured with incorrect Redis host or port.
  3. 3.Firewall blocking: iptables, ufw, or cloud security groups blocking the Redis port.
  4. 4.Redis not listening on expected interface: Redis bound to localhost only, or specific IP, not accessible from application.
  5. 5.Authentication required: Redis requires password but client isn't providing one.
  6. 6.Wrong authentication: Client using wrong password or AUTH command format.
  7. 7.Redis protected mode: Redis in protected mode rejecting external connections.
  8. 8.Unix socket vs TCP: Application trying TCP connection but Redis using Unix socket.
  9. 9.TLS/SSL required: Redis configured for TLS but client connecting without.
  10. 10.Max connections reached: Redis at maximum client connections limit.

Step 1: Check Redis Server Status

Verify Redis is running:

```bash # Check Redis service status systemctl status redis systemctl status redis-server

# Check if Redis process is running ps aux | grep redis

# Check Redis is listening netstat -tlnp | grep 6379 ss -tlnp | grep 6379

# Check all Redis ports netstat -tlnp | grep redis

# Start Redis if not running systemctl start redis-server systemctl enable redis-server

# Check Redis logs tail -f /var/log/redis/redis-server.log journalctl -u redis-server -f

# Test local connection redis-cli ping # Expected: PONG

# Check Redis info redis-cli info server

# Check client connections redis-cli client list

# Check configuration redis-cli CONFIG GET bind redis-cli CONFIG GET port redis-cli CONFIG GET protected-mode redis-cli CONFIG GET requirepass ```

Step 2: Check Network and Firewall

Ensure network allows connections:

```bash # Test local connectivity telnet localhost 6379 nc -zv localhost 6379

# Test remote connectivity telnet redis-server-ip 6379 nc -zv redis-server-ip 6379

# Check firewall (Ubuntu/ufw) ufw status ufw allow 6379/tcp

# Check firewall (CentOS/firewalld) firewall-cmd --list-all firewall-cmd --add-port=6379/tcp --permanent firewall-cmd --reload

# Check iptables iptables -L -n | grep 6379 iptables -A INPUT -p tcp --dport 6379 -j ACCEPT

# Check if Redis bound to correct interface redis-cli CONFIG GET bind # Should include the IP you're connecting from, or 0.0.0.0

# Check from remote host redis-cli -h redis-server-ip ping

# Check cloud security groups (AWS) # Ensure inbound rule allows port 6379 from application IP

# Check listening addresses ss -tlnp | grep 6379 # 0.0.0.0:6379 = listening on all interfaces # 127.0.0.1:6379 = localhost only ```

Step 3: Fix Redis Binding Configuration

Configure Redis to accept connections:

bash
# Edit Redis configuration
sudo nano /etc/redis/redis.conf

```conf # /etc/redis/redis.conf

# Bind to specific interfaces # For local only bind 127.0.0.1

# For external access bind 0.0.0.0 # Or specific IPs bind 127.0.0.1 10.0.0.1

# Protected mode - disable for external access (use with firewall) protected-mode no # Or keep enabled and use bind + requirepass

# Port port 6379

# Password authentication requirepass your-strong-password

# Max clients maxclients 10000

# Timeout for connections (0 = disabled) timeout 0

# TCP keepalive tcp-keepalive 300 ```

```bash # Restart Redis systemctl restart redis-server

# Verify settings redis-cli CONFIG GET bind redis-cli CONFIG GET protected-mode

# For immediate config change redis-cli CONFIG SET bind "0.0.0.0" redis-cli CONFIG SET protected-mode no

# Make permanent redis-cli CONFIG REWRITE ```

Step 4: Configure Authentication

Set up proper authentication:

bash
# Set password in Redis config
sudo nano /etc/redis/redis.conf
conf
requirepass your-strong-password-here

```bash # Restart Redis systemctl restart redis-server

# Connect with password redis-cli -a your-strong-password-here ping # Or redis-cli > AUTH your-strong-password-here > PING

# In application code ```

python
# Python - redis-py
import redis
r = redis.Redis(host='localhost', port=6379, password='your-password')
r.ping()
javascript
// Node.js - ioredis
const Redis = require('ioredis');
const redis = new Redis({
    host: 'localhost',
    port: 6379,
    password: 'your-password'
});
php
// PHP - Predis
$redis = new Predis\Client([
    'scheme' => 'tcp',
    'host' => 'localhost',
    'port' => 6379,
    'password' => 'your-password'
]);
java
// Java - Jedis
Jedis jedis = new Jedis("localhost", 6379);
jedis.auth("your-password");

```bash # Redis 6+ ACL authentication # Create user with specific permissions redis-cli -a admin-password > ACL SETUSER app-user on >app-password ~* +@all

# Connect as specific user redis-cli --user app-user --pass app-password ```

Step 5: Fix Protected Mode

Handle protected mode issues:

```bash # Check protected mode status redis-cli CONFIG GET protected-mode

# Option 1: Disable protected mode (use with firewall!) redis-cli CONFIG SET protected-mode no # Make permanent in config echo "protected-mode no" >> /etc/redis/redis.conf

# Option 2: Keep protected mode, use bind and password # /etc/redis/redis.conf bind 10.0.0.1 # Your server's IP protected-mode yes requirepass your-password

# Option 3: Use protected-mode with proper binding bind 127.0.0.1 10.0.0.1 protected-mode yes

# Restart Redis systemctl restart redis-server

# Verify redis-cli CONFIG GET protected-mode ```

Step 6: Configure TLS/SSL

Set up encrypted connections:

```bash # Generate certificates (self-signed for testing) openssl genrsa -out ca.key 4096 openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.pem openssl genrsa -out redis.key 2048 openssl req -new -key redis.key -out redis.csr openssl x509 -req -in redis.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out redis.pem -days 3650 -sha256

# Copy to Redis directory sudo mkdir -p /etc/redis/tls sudo cp redis.pem redis.key ca.pem /etc/redis/tls/ sudo chown redis:redis /etc/redis/tls/* sudo chmod 600 /etc/redis/tls/* ```

conf
# /etc/redis/redis.conf
port 0
tls-port 6379
tls-cert-file /etc/redis/tls/redis.pem
tls-key-file /etc/redis/tls/redis.key
tls-ca-cert-file /etc/redis/tls/ca.pem
tls-auth-clients no

```bash # Restart Redis systemctl restart redis-server

# Connect with TLS redis-cli --tls --cert /etc/redis/tls/redis.pem --key /etc/redis/tls/redis.key --cacert /etc/redis/tls/ca.pem ```

python
# Python with TLS
import redis
r = redis.Redis(
    host='localhost',
    port=6379,
    ssl=True,
    ssl_cert_reqs=None  # For self-signed
)

Step 7: Fix Connection from Application

Debug application connection issues:

```python # Python - Detailed connection debugging import redis import socket

try: r = redis.Redis( host='redis-server', port=6379, password='your-password', socket_timeout=5, socket_connect_timeout=5, retry_on_timeout=True ) r.ping() print("Connected successfully") except redis.ConnectionError as e: print(f"Connection failed: {e}") # Debug DNS print(f"DNS resolution: {socket.gethostbyname('redis-server')}") except redis.AuthenticationError as e: print(f"Authentication failed: {e}") ```

```javascript // Node.js - Connection debugging const Redis = require('ioredis');

const redis = new Redis({ host: 'redis-server', port: 6379, password: 'your-password', connectTimeout: 10000, retryStrategy: (times) => { console.log(Retry attempt: ${times}); if (times > 3) { console.log('Max retries reached'); return null; } return Math.min(times * 200, 2000); } });

redis.on('connect', () => console.log('Connected')); redis.on('error', (err) => console.log('Error:', err)); redis.on('close', () => console.log('Connection closed')); ```

Step 8: Handle Max Connections

Fix connection limit issues:

```bash # Check current connections redis-cli client list | wc -l

# Check max clients redis-cli CONFIG GET maxclients

# Check file descriptor limit cat /proc/$(pidof redis-server)/limits | grep "open files"

# Increase max clients in config # /etc/redis/redis.conf maxclients 10000

# Increase system limits sudo nano /etc/security/limits.conf ```

bash
redis soft nofile 65535
redis hard nofile 65535
bash
# For systemd, create override
sudo systemctl edit redis-server
ini
[Service]
LimitNOFILE=65535

```bash # Restart Redis systemctl restart redis-server

# Verify redis-cli CONFIG GET maxclients ```

Step 9: Create Connection Test Script

Build diagnostic tool:

```bash #!/bin/bash # test_redis_connection.sh

HOST=${1:-"localhost"} PORT=${2:-6379} PASSWORD=${3:-""}

echo "=== Redis Connection Test ===" echo "Host: $HOST" echo "Port: $PORT" echo ""

echo "1. DNS Resolution" echo "-----------------" if [[ "$HOST" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "Using IP address directly" else nslookup $HOST | head -5 fi echo ""

echo "2. Network Connectivity" echo "----------------------" nc -zv -w2 $HOST $PORT 2>&1 echo ""

echo "3. Redis CLI Connection" echo "----------------------" if [ -n "$PASSWORD" ]; then redis-cli -h $HOST -p $PORT -a "$PASSWORD" ping else redis-cli -h $HOST -p $PORT ping fi echo ""

echo "4. Redis Server Info" echo "-------------------" if [ -n "$PASSWORD" ]; then redis-cli -h $HOST -p $PORT -a "$PASSWORD" INFO server 2>/dev/null | head -20 else redis-cli -h $HOST -p $PORT INFO server 2>/dev/null | head -20 fi echo ""

echo "5. Connected Clients" echo "-------------------" if [ -n "$PASSWORD" ]; then redis-cli -h $HOST -p $PORT -a "$PASSWORD" CLIENT LIST 2>/dev/null | wc -l else redis-cli -h $HOST -p $PORT CLIENT LIST 2>/dev/null | wc -l fi echo "connected clients" echo ""

echo "6. Memory Usage" echo "---------------" if [ -n "$PASSWORD" ]; then redis-cli -h $HOST -p $PORT -a "$PASSWORD" INFO memory 2>/dev/null | grep "used_memory_human" else redis-cli -h $HOST -p $PORT INFO memory 2>/dev/null | grep "used_memory_human" fi echo ""

echo "=== Test Complete ===" ```

Step 10: Monitor Redis Connections

Set up monitoring:

```bash #!/bin/bash # monitor_redis.sh

REDIS_HOST=${1:-"localhost"} REDIS_PORT=${2:-6379} ALERT_THRESHOLD=${3:-1000}

while true; do CONNECTIONS=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT CLIENT LIST 2>/dev/null | wc -l) MEMORY=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT INFO memory 2>/dev/null | grep used_memory_rss_human | cut -d: -f2 | tr -d '\r')

echo "$(date): Connections=$CONNECTIONS Memory=$MEMORY"

if [ "$CONNECTIONS" -gt "$ALERT_THRESHOLD" ]; then echo "WARNING: High connection count: $CONNECTIONS" # Send alert # curl -X POST $WEBHOOK -d "High Redis connections: $CONNECTIONS" fi

sleep 60 done ```

Checklist

StepActionVerified
1Checked Redis server status
2Checked network and firewall
3Fixed Redis binding configuration
4Configured authentication
5Fixed protected mode
6Configured TLS/SSL
7Fixed connection from application
8Handled max connections
9Created connection test script
10Set up monitoring

Verify the Fix

  1. 1.Test connection:
  2. 2.```bash
  3. 3.redis-cli -h localhost ping
  4. 4.`
  5. 5.Check from application:
  6. 6.```python
  7. 7.import redis
  8. 8.r = redis.Redis()
  9. 9.print(r.ping()) # Should print True
  10. 10.`
  11. 11.Monitor connections:
  12. 12.```bash
  13. 13.redis-cli CLIENT LIST
  14. 14.`
  • [Fix Redis Memory Usage High](/articles/fix-redis-memory-usage-high)
  • [Fix Redis Cluster Not Working](/articles/fix-redis-cluster-not-working)
  • [Fix Redis Persistence Failed](/articles/fix-redis-persistence-failed)
  • [Fix Redis Replication Lag](/articles/fix-redis-replication-lag)
  • [Fix Redis Key Eviction Issues](/articles/fix-redis-key-eviction-issues)