Why Redis?

What we have learned so far is not enough to build anything other than the most basic websites or apps. We are missing a key piece of the puzzle: how to connect our Rails app to external services like a database. Here, we will learn how to do just that, starting with Redis.Redis

Why Redis before a database?

Because, while the process of adding services to our app is similar, it turns out that Redis is easier to integrate into our app than a database. In fact, this will teach you the basic skills needed to add any service to your app, be it a database, background workers, Elasticsearch, or even a separate JavaScript front end. Soon our Docker-fueled apps will be every bit as powerful as we are used to, and then some.

Starting a Redis server

We want our Rails app to talk to Redis. First, we are going to need a Redis server that our application can talk to. As you might expect, we are not going to install and run Redis on our local machine. Instead, let’s leverage the power of Docker and start a Redis server inside a container. Ultimately, we want to add Redis as a new service with Compose. However, since this is the first service we have added, we are going to take baby steps.

We will start by seeing how to run Redis in a container using docker run before we circle back to get Compose to do this for us automatically. As you gain more experience and confidence, you will be able to skip this first step and jump straight to setting up a service in Compose.

Using docker run

To start a Redis server with docker run, issue the following command:

$ docker run --name redis-container redis 

This command should mostly be familiar. It tells Docker to run a container based on the official Docker redis image. However, there are a couple of options we have not seen before.

Docker gives each new container a unique container ID to identify it. However, these long identifiers are not very human-friendly. Just like when we tag an image to give it a friendlier name, the --name option tells Docker to give our new container a nice, human-readable name.

You can stop the Redis server by pressing Ctrl+C.

Using Compose

Our ultimate aim is for our docker-compose.yml file to fully describe our application, including all its dependencies. Having seen how to start a Redis server with docker run, we are ready to set up Compose to manage Redis for us.

Let’s modify our existing docker-compose.yml file to include a new service that we will call redis:

Get hands-on with 1200+ tech skills courses.