Search code examples
phplaravelredisphpredis

Unable to Connect to Redis (TLS) with Laravel, but TCP works fine


I'm using Upstash Redis with TLS connection, but I'm always getting connection lost, redis exception, timed out 2 minutes, when trying to connect to Redis. If I use TCP, it works fine.

Using localhost, http://127.0.0.1:8000, Laravel server using php artisan serve. Can http connect to redis over tls?

I'm following the upstash laravel guide and my config seems accurate based on laravel docs, only changes for tls is the scheme.

.env

CACHE_DRIVER=redis

REDIS_CLIENT=phpredis
# Adding tls:// infront of the redis host still gives the same connection lost error
REDIS_HOST=my-upstash-redis-84191.upstash.io
REDIS_PASSWORD=UPSTASH_REDIS_PASS
REDIS_PORT=34704
REDIS_CACHE_DB=0

config/database.php


    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
            'read_write_timeout' => 60,
        ],

        'cache' => [
            // Commented out scheme when using tcp and redis connection works
            'scheme' => 'tls', 
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

Testing Redis connection API call

use Illuminate\Support\Facades\Redis;

// TLS Redis gives connection lost after 2 minutes
// http://127.0.0.1:8000/api/redis -> RedisException Connection Lost 

// TCP Redis connects to redis and returns null, since 'test' key doesn't exist
Route::get('/redis', function () {
    // Should return null, no test key in redis
    $data = Redis::get('test');

    return [
        'redis' => $data
    ];
});

I used predis before and switched to phpredis as I thought that was the issue. Since I can connect to redis with tcp, just not tls. Are there special instructions and values needed beyond the scheme = tls to get redis working?

Versions

"php": "^8.2.0",
"laravel/framework": "^10.0",

PHPRedis: 5.3.7

Solution

  • I am also facing the same error using upstash and phpredis. If I do not use the TLS, I can connect just fine. The error only persists when I am using the TLS. Have you found any solution?

    Edit: I solved this by prepending tlsv1.2:// to REDIS_HOST key in the .env file and removing the 'scheme' => 'tls' from the config/database.php file.