Click here to Skip to main content
14,297,345 members

Running Redis as a Windows Service

Rate this:
4.96 (23 votes)
Please Sign up or sign in to vote.
4.96 (23 votes)
31 Jan 2014CPOL
A utility to run Redis, or other executables, as a Windows Service.


In this article I will show how to run the Window version of Redis Server, or other executables, as a Windows service.

Here at CodeProject, we use Redis as a distributed cache. We store massive amounts of information such as Articles, Forum Messages and retrieve these items from the cache rather than the database.

Redis alllows us to store and retrieve full documents, rather than querying SQL for the various pieces and composing and formatting the document on each request. This is possible on our site because most of the information is read a lot more than it is written, and some information, such as number of views, can be a little stale.

While in production we run Redis on a Linux server, in out development environment we are running the Microsoft port of Redis on a Window 7 desktop. The problem is that Redis is not designed to be run as a Windows Service. This means that someone had to logon and run the Redis executable. This was fine when Chris was the only one logging into the server, but last week, I had to connect to install a copy of our Search Server for development purposes. Needless to say, this logged Chris off, and killed the Redis Server. I restarted it under my session.

Back on my machine, I am fixing a subtle caching bug, and when I start testing, the code is acting like there is a connection failure to the Redis Server. As the code I am changing is related to the detection of problems with the connection to Redis, I spin my wheels for half an hour or so before I realize that Chris has remoted into the server, killing my session and the Redis Server.

Both Chris and I tried a number of recommended methods for running Redis as a Windows Service, without any success. Having written several Windows Services to support various CodeProject processes, I decided to write a utility which would allow us to install and run an exe as a Windows Service. This utility is called Exe2Srvc.

Using Exe2Srvc

Exe2Srv is a program that can be run as either a console application or installed as a Windows Service. This application reads the path to an executable, and the command line arguments from it .config file and then starts a the executable in a new Process.

The simplest way to use the executable is to

  1. copy the files in the binfiles download, or from bin/Release from the compiled source, into the directory containing the executable you wish to run as a Service.
  2. Edit the "Cmd" and "CmdArgs" values in the Exe2Srvc.exe.config to contain the full path to the executable, and the command line arguments required.
  3. Run the Install.bat file from a 'Run as Administrator' command shell.
  4. Use the Service Manager to:

    • set the start mode to Automatic
    • set the Recovery options. I usually set them to "Restart Service".
    • start the Service.

For my tests, I downloaded Redis from Nuget, and copied the files from the /packages/Redis- under the solution directory to C:/Redis. I then copied the files from Exe2Srvc\bin\Release to the same directory.

The Exe2Srvc.exe.config file contains:

<?xml version="1.0" encoding="utf-8" />
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
        <!-- set Cmd to the executable file name. -->
        <!-- set CmdArg to any command arguments required. -->
        <add key="Cmd"      value="c:\Redis\redis-server.exe"/>
        <add key="CmdArgs"  value="c:\Redis\redis.conf --port 6379"/> 

If the path to the executable includes spaces, then the path needs to be in quotes. This can be accomplished by enclosing the double-quoted string in single-quotes as shown below.

<?xml version="1.0" encoding="utf-8" />
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
        <!-- set Cmd to the executable file name. -->
        <!-- set CmdArg to any command arguments required. -->
        <add key="Cmd"      value='"c:Program Files\Redis\redis-server.exe"'/>
        <add key="CmdArgs"  value="c:\Redis\redis.conf --port 6379"/> 

The Install.bat file, which must be run as an Administrator, uses the SC command to install the Service.

sc create Redis binpath= "c:\Redis\Exe2Srvc.exe"

Then I use the Services Manager to configure the Service and start it.

Service Manager

Double Click on the Redis service to open the properties editor and select the Recovery tab. Set the options to restart the service on errors as shown.

 Service Manager

Select the General tab. 

  • Set the Startup Type to Automatic,
  • click the Start button
  • and click the OK button.
Service Manager

Redis is now installed and running as a Windows Service. Use the redis-cli.exe to test the connection.

How Exe2Srvc works 

Creating a console application that can be run as a Windows Service used a technique shown to me by Steve Smith and based on an article Run Windows Service as a console program by Einar Egilsson.

Basically you create a console application, and change the Program class to derive from ServiceBase. In the Main, the Environment.UserInteractive property is used to determine whether the program is being run from the command line, or run as a Service.

The required command and commandline parameters are read from the LoadConfiguration method.

/// <summary>
/// Loads the configuration parameters from the application config file
/// </summary>
private void LoadConfiguration
    // Load the executable filename and command arguements from config file.
    _cmd     = ConfigurationManager.AppSettings["Cmd"];
    _cmdArgs = ConfigurationManager.AppSettings["CmdArgs"];
    if (string.IsNullOrWhiteSpace(_cmd))
        throw new Exception("The appsetting 'Cmd' was not defined in the config file.");

This is called from the OnStart method which is called from Main when started as a console application, or by the Service infrastructure when run as a Service. OnStart runs the executable in a new Process as shown below.

/// <summary>
/// When implemented in a derived class, executes when a Start command is sent to the
/// service by the Service Control Manager (SCM) or when the operating system starts
/// (for a service that starts automatically).
/// Specifies actions to take when the service starts.
/// </summary>
/// <param name="args";>
/// Data passed by the start command.
/// </param>
protected override void OnStart(string[] args)
    if (Environment.UserInteractive)
        string message = String.Format"Starting {0} at {1}.", _serviceName, DateTime.Now);
    // loading the configuration file info here allows the service to be stopped,
    // the configuration modified, and the service restarted.
     // Start the executable.
      ProcessStartInfo procInfo = new ProcessStartInfo(_cmd);
      procInfo.UseShellExecute = false;
       if (!string.IsNullOrWhiteSpace(_cmdArgs))
           procInfo.Arguments = _cmdArgs;
       _process = Process.Start(procInfo);

When the Service is stopped, the OnStop method is called. This kills the Process, waits for it to terminate, and disposes of the Process. Make sure you wait for the Process to terminate, failure to do so will result in improperly stopped Services that are difficult to remove and fix.

/// <summary>
/// When implemented in a derived class, executes when a Stop command is sent to the service
/// by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
/// </summary>
/// <remarks>Stops the background tasks.</remarks>
protected override void OnStop()
    if (Environment.UserInteractive)
        string message = String.Format("Stopping {0} at {1}.", _serviceName, DateTime.Now);
     // Kill the process
     if (_process != null)
         _process = null;

Points of Interest

I've attempted to make this as simple and flexible as possible, but it only meets my original requirement of being able to run the Windows version of Redis as a Windows Server. If you have additional requirement, feel free to modify the code to match your needs.


This is the original release.

31 Jan, 2014 - added example of specifying an executable path that contains spaces. 



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Matthew Dennis
Software Developer (Senior) CodeProject
Canada Canada
As Senior Architect, Matthew is responsible for the Architecture, Design, and Coding of the CodeProject software as well as Manager of the Infrastructure that runs the web site.

Matthew works on improving the performance and experience of the Code Project site for users, clients, and administrators.

Matthew has more years of software development, QA and architecture experience under his belt than he likes to admit. He graduated from the University of Waterloo with a B.Sc. in Electrical Engineering. He started out developing micro-processor based hardware and software including compilers and operating systems.
His current focus is on .NET web development including jQuery, Webforms, MVC, AJAX, and patterns and practices for creating better websites.
He is the author of the Munq IOC, the fastest ASP.NET focused IOC Container.
His non-programming passions include golf, pool, curling, reading and building stuff for the house.

Comments and Discussions

QuestionIssues Pin
Michael Chao18-May-17 8:47
memberMichael Chao18-May-17 8:47 
QuestionIt works as expected, good Pin
Michael Chao18-May-17 8:32
memberMichael Chao18-May-17 8:32 
QuestionMsOpentech Redis Port Vs this Solution Pin
Ehsan A Samani22-Oct-15 18:58
professionalEhsan A Samani22-Oct-15 18:58 
QuestionUseful work, my 5 Pin
Sergey Alexandrovich Kryukov8-Aug-14 12:06
memberSergey Alexandrovich Kryukov8-Aug-14 12:06 
GeneralMy vote of 1 Pin
123439546-May-14 17:53
member123439546-May-14 17:53 
GeneralRe: My vote of 1 Pin
Tachyonx27-Jan-15 2:39
memberTachyonx27-Jan-15 2:39 
GeneralRe: My vote of 1 Pin
Michael Chao18-May-17 8:36
memberMichael Chao18-May-17 8:36 
Questionhandling of failure Pin
salvakg2-May-14 1:28
membersalvakg2-May-14 1:28 
GeneralMy vote of 5 Pin
Dr Bob27-Jan-14 8:14
memberDr Bob27-Jan-14 8:14 
QuestionWhat about RedisWatcher? Pin
Howard Robinson26-Jan-14 19:38
memberHoward Robinson26-Jan-14 19:38 
AnswerRe: What about RedisWatcher? Pin
Matthew Dennis27-Jan-14 6:51
adminMatthew Dennis27-Jan-14 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 25 Jan 2014


29 bookmarked