.net core, Redis

Connect to a Redis container hosted in Docker from a .NET Core application

Recently I wrote a post on how to install Redis to Windows, and then connect from a .NET Core application. But what about just getting a Redis container from the Docker hub and connecting to that, instead of installing Redis locally?

Step 1: Start a new Redis instance

Open a PowerShell prompt, and run the following command:

docker run -d --name myRedis -p 6379:6379 redis

This simple command creates and runs a container named “myRedis” which is accessible through port 6379.

Step 2: Connect with the connection string “localhost:6379”

In my previous post I stored my Redis connection string in an environment variable. Because this was for a locally installed instance of Redis, I was able to use the connection string of “localhost”. However with the Docker container, my connection string now needs to be “localhost:6379”.

But environment variables are easy to change – now I can open a PowerShell prompt with administrative privileges and update my environment variable:

[Environment]::SetEnvironmentVariable("REDIS_CONNECTIONSTRING", "localhost:6379", "Machine")

Now if I use the C# classes that I wrote about in my previous post (which are on GitHub here), my application will happily connect to the new Redis container, and read and write data to the Redis server.

Wrapping up

This post shows how you can create a local Docker container running Redis, and then connect to it from a .NET application. The benefit here is that you now don’t need to install Redis to your development environment – instead you can a single line of code and have Redis up and running in a few seconds.