LESSON 6 OF 12

6. Installing Redis with Docker and Integrating It with ASP.NET Core

In this lesson, you will run Redis with Docker Compose, add connection settings to an ASP.NET Core application, and configure the Redis provider for IDistributedCache. You will also verify connectivity, test restarts and container lifecycle behavior, and troubleshoot common configuration errors.

45 dk 74

Introduction

In the previous lesson, we created a cache abstraction based on IDistributedCache. This abstraction prevents application code from depending directly on a specific cache technology. However, for the application to use a real distributed cache, a Redis service must be available and the ASP.NET Core application must connect to it correctly.

In this lesson, we will run Redis with Docker Compose instead of installing it directly on the host operating system. This approach gives development teams a repeatable environment, keeps the Redis version explicit, and makes starting and stopping the service straightforward. We will then use the Microsoft.Extensions.Caching.StackExchangeRedis package to configure the Redis implementation behind IDistributedCache.

By the end of the lesson, you will understand how cache data behaves when the application restarts, what happens when the Redis container is stopped, and why connection settings must change according to the environment in which the application runs.

1. Preparing the development environment

The examples use Docker Desktop or Docker Engine together with Docker Compose. A simple project structure can look like this:

src/CacheDemo.Api/CacheDemo.Api.csproj
src/CacheDemo.Api/Program.cs
src/CacheDemo.Api/appsettings.json
docker-compose.yml

Running Redis in a container instead of installing it directly on the host helps every developer use the same service version. In production, however, a single local container is rarely sufficient. Managed Redis, high availability, replication, monitoring, backup, and security requirements must be evaluated separately.

2. Defining Redis with Docker Compose

Create a docker-compose.yml file in the project root:

services:
  redis:
    image: redis:7-alpine
    container_name: cache-demo-redis
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    command: redis-server --appendonly yes
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  redis-data:

In this file, redis is the service name inside the Compose network. The 6379:6379 mapping forwards port 6379 on the host to port 6379 inside the container. If the application runs on the host, its address is localhost:6379. If the application runs in another container, do not use localhost; use the Redis service name, redis:6379.

The named volume called redis-data separates Redis's /data directory from the container lifecycle. The --appendonly yes option enables Append Only File persistence. Nevertheless, persistence does not turn Redis into the primary source of business data. Redis should still be treated as a cache layer that can be rebuilt.

The healthcheck executes redis-cli ping to verify that Redis is accepting requests and can return PONG. A container being in a running state is not identical to the service being ready, so health checks are valuable when multiple services are started together.

Starting and inspecting the service

docker compose up -d
docker compose ps
docker compose logs redis

You can connect with the client inside the container and run a basic test:

docker compose exec redis redis-cli ping
# PONG

docker compose exec redis redis-cli set demo:message "hello"
docker compose exec redis redis-cli get demo:message
# "hello"

If these commands succeed, Redis is running, listening on port 6379, and accepting basic commands.

3. Adding the ASP.NET Core Redis package

Add the Redis provider for IDistributedCache to the project:

dotnet add src/CacheDemo.Api package Microsoft.Extensions.Caching.StackExchangeRedis

This package provides the AddStackExchangeRedisCache extension method. Instead of using ConnectionMultiplexer directly throughout the application, we select the framework integration so that our existing cache abstraction can continue to depend on IDistributedCache.

For local development, add the following setting to appsettings.Development.json:

{
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  },
  "Redis": {
    "InstanceName": "cache-demo:"
  }
}

If the connection string contains a username or password, do not store it in source control. Use User Secrets, environment variables, or a secure secret store in production. In this simple local example, Redis authentication is not enabled, so the host and port are sufficient.

4. Configuring the IDistributedCache provider

Read the Redis connection from configuration and register the provider in Program.cs:

using Microsoft.Extensions.Caching.StackExchangeRedis;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddHealthChecks();

var redisConnection = builder.Configuration.GetConnectionString("Redis")
    ?? throw new InvalidOperationException(
        "ConnectionStrings:Redis is missing.");

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = builder.Configuration["Redis:InstanceName"]
        ?? "cache-demo:";
});

var app = builder.Build();

app.MapControllers();
app.MapHealthChecks("/health");

app.Run();

InstanceName can add a common prefix to keys generated by the provider. For example, an application key such as products:42 may appear in Redis as cache-demo:products:42. If multiple applications share one Redis server, a namespace helps reduce key collisions.

In this example, the connection setting is required explicitly. Failing fast when the setting is missing is usually better than silently switching to an unintended cache implementation. It makes incorrect environment configuration visible during startup.

5. Selecting the connection address by environment

The connection address depends on where the application runs:

Application locationRedis addressExplanation
Host operating systemlocalhost:6379Uses the published host port.
Same Compose networkredis:6379The service name acts as a DNS name.
Remote Redisserver-address:6379Security, TLS, and authentication must be configured separately.

If the API also runs inside Compose, define the setting with an environment variable:

services:
  api:
    build: ./src/CacheDemo.Api
    environment:
      ConnectionStrings__Redis: redis:6379
      Redis__InstanceName: cache-demo:
    depends_on:
      redis:
        condition: service_healthy

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

In ASP.NET Core configuration, two underscores represent the colon used in JSON configuration keys. Therefore, ConnectionStrings__Redis maps to ConnectionStrings:Redis. The depends_on and service_healthy settings help prevent the API container from starting before Redis passes its health check. They do not eliminate every runtime network failure, so the application should still handle connection interruptions safely.

6. Verifying the connection through the application

Reading a configuration value during startup does not prove that Redis can actually be used. You can add a small test endpoint that uses the cache abstraction from the previous lesson:

using Microsoft.Extensions.Caching.Distributed;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/cache-test")]
public sealed class CacheTestController : ControllerBase
{
    private readonly IDistributedCache _cache;

    public CacheTestController(IDistributedCache cache)
    {
        _cache = cache;
    }

    [HttpGet("{key}")]
    public async Task<IActionResult> Get(string key, CancellationToken cancellationToken)
    {
        var value = await _cache.GetStringAsync(key, cancellationToken);

        if (value is null)
        {
            value = $"created-at:{DateTimeOffset.UtcNow:O}";
            await _cache.SetStringAsync(
                key,
                value,
                new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                },
                cancellationToken);

            return Ok(new { key, value, source = "database-or-origin" });
        }

        return Ok(new { key, value, source = "redis" });
    }
}

Run the API and call the endpoint twice. The first request should be a cache miss, while the second should be a cache hit. You can inspect the key from inside Redis:

docker compose exec redis redis-cli --scan --pattern 'cache-demo:*'

The exact prefix can depend on the provider version and configuration. Do not build production assumptions around a key format without inspecting the keys generated by your own application.

7. Restarting the application and managing the container lifecycle

Restarting the application

If the application is stopped and restarted while Redis continues running as a separate service, the cached value remains in Redis. This is an important difference from local IMemoryCache. At the same time, entries whose expiration has passed will no longer be available, and the application may need to repopulate its cache.

Stopping the Redis container

docker compose stop redis
docker compose ps

API operations that access Redis may now produce connection errors. Keep cache access separate from critical business workflows. In some scenarios, falling back to the primary data source is appropriate, but an unrestricted fallback on every request can suddenly overload the database. This problem is closely related to cache resilience and stampede prevention, which will be addressed later in the course.

Recreating the container

docker compose up -d --force-recreate redis

Because a named volume is used, recreating the Redis container does not remove the volume. In contrast, the following command also removes the volume:

docker compose down -v

This is useful for a clean local reset, but in a real environment deleting a volume can cause data loss. Even if cache data is rebuildable, this command should be used deliberately.

8. Common mistakes and troubleshooting

  • Connection refused: The Redis container may be stopped, the port mapping may be missing, or the application may be using the wrong port. Check docker compose ps, docker compose logs redis, and redis-cli ping.
  • Using localhost from an application container: Inside a container, localhost refers to that application container, not the Redis container. Use redis:6379 on the Compose network.
  • Port collision: If another process uses host port 6379, map 6380:6379. A host-based application uses localhost:6380, while an application on the Compose network still uses redis:6379.
  • Incorrect configuration key: ConnectionStrings:Redis and Redis:ConnectionString are different keys. Ensure that the JSON, environment variable, and C# code use the same naming.
  • Starting the API before Redis is ready: Short-form depends_on controls creation order but does not guarantee that Redis is ready to accept requests. Use a health check and service_healthy.
  • Putting secrets in the Compose file: Do not commit passwords, certificates, or production connection strings to source control. Use environment variables, secrets, or a secure configuration service.
  • Exposing Redis to the internet: Publishing a port is convenient for local development. In production, restrict network access and configure authentication and TLS according to the provider's security requirements.

9. Short practice exercise

Complete the following steps:

  1. Create docker-compose.yml with a Redis service, a named volume, and a health check.
  2. Start Redis with docker compose up -d and verify it with docker compose exec redis redis-cli ping.
  3. Add the Microsoft.Extensions.Caching.StackExchangeRedis package.
  4. Configure ConnectionStrings:Redis as localhost:6379.
  5. Register the Redis-backed IDistributedCache with AddStackExchangeRedisCache.
  6. Write and read a key, then verify that the second request comes from Redis.
  7. Restart the API and test whether the same key still exists.
  8. Run docker compose down -v and verify that the key disappears after the volume is removed.

As an additional challenge, run the API inside a container and change the connection string to redis:6379. Comparing the two network contexts will help you understand the most common Docker connection mistake: using localhost where a service name is required.

Conclusion

In this lesson, we ran Redis reproducibly with Docker Compose, added a named volume and health check, read the connection from ASP.NET Core configuration, and connected IDistributedCache to the Redis provider. We also examined the difference between host networking and container networking, the use of double underscores in environment variables, and the effect of container lifecycle operations on cache data.

Your cache abstraction from the previous lesson now runs on a real distributed cache. The next step is to manage Redis keys, serialization, and cache lifetimes more deliberately. The goal is not merely to start Redis, but to ensure that the application can use the same cache contract reliably across development, testing, and production environments.

Sources