Search code examples
c#docker-composerediswebapi

Connection between C# Web api and redis cache containers


I try to connect from C# web api to redis database, but it always fail with error:

"No connection is active/available to service this operation: EVAL; UnableToConnect on http://localhost:6379:6379/Interactive, Initializing/NotStarted, last: NONE, origin: BeginConnectAsync, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: Connecting, mgr: 10 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.2.4.27433, mc: 1/1/0, mgr: 10 of 10 available, clientName: d252797b3b96, IOCP: (Busy=0,Free=1000,Min=1,Max=1000), WORKER: (Busy=1,Free=32766,Min=8,Max=32767), v: 2.2.4.27433\n at StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl[T](Message message, ResultProcessor1 processor, ServerEndPoint server) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 2798\n at StackExchange.Redis.RedisBase.ExecuteSync[T](Message message, ResultProcessor1 processor, ServerEndPoint server) in //src/StackExchange.Redis/RedisBase.cs:line 54\n at StackExchange.Redis.RedisDatabase.ScriptEvaluate(String script, RedisKey[] keys, RedisValue[] values, CommandFlags flags) in //src/StackExchange.Redis/RedisDatabase.cs:line 1189\n at Microsoft.Extensions.Caching.StackExchangeRedis.RedisCache.Set(String key, Byte[] value, DistributedCacheEntryOptions options)\n at Program.<>c.<$>b__0_1(String name, String val, IDistributedCache cache) in /src/Program.cs:line 25".

But if I try to connect not from the container, then everything works fine.

Program.cs:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["RedisConnection"];
});

docker-compose.yaml:

version: "3.7"
services:
  web-api:
    build: ./WebAPI
    image: webapi
    container_name: api
    ports:
      - "3000:80"
    environment:
      - RedisConnection=http://localhost:6379
    depends_on:
      - cache
  cache:
    image: redis
    container_name: redis_cache
    ports:
      - "6379:6379"

Solution

  • The Redis connection string is not correct as it should be in the form host:port (where port is, by default, 6379) and Redis does not use the HTTP protocol at all; also the host is not localhost in your case but redis_cache, as Redis is served by that container.

    Your docker-compose.yaml should thus have the RedisConnection environment line fixed in this way:

        environment:
          - RedisConnection=redis_cache