In this article I'm going to show you how to run Redis in a multi-container applications on Docker.

I suppose you have docker and docker-compose installed on your system.

Creating docker-compose.yml file

To run Redis with docker-compose we will use the docker-compose file named docker-compose.yml:

version: "3.3"

services:
	redis-cache:
        image: 'redis:alpine'
        container_name: redis-cache
        ports:
            - '6379:6379'
        volumes:
            - redis-data:/data
            - ./redis.conf:/data/redis.conf
        networks:
            - app-network
        command: redis-server /data/redis.conf
        healthcheck:
            test: [ "CMD", "redis-cli", "ping" ]
            retries: 3
            timeout: 5s
networks:
    app-network:
        driver: bridge

volumes:
    redis-data:

We are going to use ./redis.conf file as Redis config. If you are ok to go with default config, you can easily remove following lines:

- ./redis.conf:/data/redis.conf

command: redis-server /data/redis.conf

The next thing with should do before run Redis in a container is create s config file redis.conf:

maxmemory 100mb
maxmemory-policy volatile-lfu
requirepass "my-super-secure-redis-password"

To get more info about Redis configuration options, please follow the official documentation

Running Redis in a docker container

After we have created both docker-compose.yml and redis.conf files, we can start our new container.

To run Redis in a container just type

$ docker-compose up -d

If you run this command first time, it make take some time to download Redis image and run a container.

Checking if container started

To get list of all started containers you can run

$ docker ps

in a response of this command you will get something like that:

CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS                    PORTS                      NAMES
df8f9f121c45   redis:alpine   "docker-entrypoint.s…"   6 days ago    Up 30 seconds (healthy)   0.0.0.0:6379->6379/tcp     redis-cache

Connect to redis instance via redis-cli

To connect to our Redis instance via redis-cli we should run redis-cli inside a container:

$ docker exec -it redis-cache redis-cli

In a response of the command, you will get:

127.0.0.1:6379>

And you are ready to make some tests:

127.0.0.1:6379> auth "my-super-secure-redis-password"
OK
127.0.0.1:6379> set "test_key" "test_value"
OK
127.0.0.1:6379> get "test_key"
"test_value"
127.0.0.1:6379> keys *
1) "test_key"
127.0.0.1:6379>

To dive deeper in Redis commands world, follow the official documentation