Get Redis up and running quickly with Docker Compose

Good day! Today I'll show you how to quickly and efficiently set up Redis using Docker Compose. This process will only take a few minutes, but the result will be a fully functional Redis database running in an isolated Docker container. Important components such as cache and configuration data will be stored on your local machine using volumes, ensuring data reliability and availability.

What is Redis and why is it needed?

Redis Remote Dictionary Server is a high-performance, in-memory key-value database management system. Redis is often used for data caching, session management, message queuing, and as a NoSQL database for fast data access.

Main advantages of Redis:

  • Speed: Working in memory ensures fast query processing.

  • Simplicity: a simple key-value data model with support for complex data structures.

  • Flexibility: support for various data structures such as strings, lists, sets, hashes, etc.

  • Scalability: ease of scaling and replication support.

Preparation

Before you can start deploying Redis on your local machine or VPS server, you need to install Docker and Docker Compose.

If you are new to using Docker, I recommend starting with installation Docker Desktop on your local computer. This app will automatically install Docker and Docker Compose, making it easy to get started with containerization.

Step 1: Create a Docker Compose File

Create an empty directory and move into it. In the created directory we will create a file docker-compose.yaml, which will describe our Redis service. Here is an example of my file:

version: '3.9'

services:
  redis:
    image: redis:latest
    container_name: redis_container
    environment:
      - REDIS_PASSWORD=${REDIS_PASSWORD}
      - REDIS_USER=${REDIS_USER}
      - REDIS_USER_PASSWORD=${REDIS_USER_PASSWORD}
    ports:
      - "6380:6379"
    volumes:
      - ./redisdata:/data
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 256M
    command: >
      sh -c '
        mkdir -p /usr/local/etc/redis &&
        echo "bind 0.0.0.0" > /usr/local/etc/redis/redis.conf &&
        echo "requirepass $REDIS_PASSWORD" >> /usr/local/etc/redis/redis.conf &&
        echo "appendonly yes" >> /usr/local/etc/redis/redis.conf &&
        echo "appendfsync everysec" >> /usr/local/etc/redis/redis.conf &&
        echo "user default on nopass ~* +@all" > /usr/local/etc/redis/users.acl &&
        echo "user $REDIS_USER on >$REDIS_USER_PASSWORD ~* +@all" >> /usr/local/etc/redis/users.acl &&
        redis-server /usr/local/etc/redis/redis.conf --aclfile /usr/local/etc/redis/users.acl
      '
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "$REDIS_PASSWORD", "ping"]
      interval: 30s
      timeout: 10s
      retries: 5
    restart: unless-stopped
    tty: true
    stdin_open: true

Create a .env file in the same directory and add the following parameters to it (enter your own data):

REDIS_PASSWORD=my_redis_password
REDIS_USER=my_user
REDIS_USER_PASSWORD=my_user_password

A quick overview of the Docker Compose file

  • Version:

  • Redis service:

    • image: Image used redis:latest.

    • container_name: The created container will have a name redis_container.

    • environment: Environment Variables:

      • REDIS_PASSWORD: Password for Redis (default username is default).

      • REDIS_USER: New user name.

      • REDIS_USER_PASSWORD: Password for new user.

    • ports: Forward port 6380 (local machine, server) to 6379 (port inside the Redis container) to access Redis (for access you will need to specify port 6380).

    • volumes: Storing Redis data in a local directory ./redisdata. This way, your data will be saved in a local folder and you won't lose it even if the Redis container is accidentally deleted or you lose access to it. The main thing is to ensure the safety of data from the folder redisdata

    • deploy: Limitations and resource reservation:

    • command:

      1. mkdir -p /usr/local/etc/redis: This command creates a directory /usr/local/etc/redis, if it doesn't exist. Flag -p allows you to create subdirectories if necessary.

      2. echo "bind 0.0.0.0" > /usr/local/etc/redis/redis.conf: Here we add the line "bind 0.0.0.0" to file redis.conf. This allows Redis to listen for connections from all IP addresses.

      3. echo "requirepass $REDIS_PASSWORD" >> /usr/local/etc/redis/redis.conf: This command adds a password line to the file redis.conf. The password is taken from the environment variable $REDIS_PASSWORD.

      4. echo "appendonly yes" >> /usr/local/etc/redis/redis.conf: Here we enable log mode (append-only mode) to save data to disk.

      5. echo "appendfsync everysec" >> /usr/local/etc/redis/redis.conf: This line tells Redis to synchronize the log to disk every second.

      6. echo "user default on nopass ~* +@all" > /usr/local/etc/redis/users.acl: Here we create a file users.acl and add an access rule for the default user. It can connect without a password and has access to all commands (~* +@all).

      7. echo "user $REDIS_USER on >$REDIS_USER_PASSWORD ~* +@all" >> /usr/local/etc/redis/users.acl: This command adds an access rule for a specific user (with the name specified in the variable $REDIS_USER). User must provide password from variable $REDIS_USER_PASSWORD.

      8. redis-server /usr/local/etc/redis/redis.conf --aclfile /usr/local/etc/redis/users.acl: Here we start the Redis server with the specified configuration file and ACL file.

    • healthcheck: Service health check:

      • Team redis-cli ping with a password.

      • Interval 30 seconds, timeout 10 seconds, 5 attempts.

    • restart: Restart Policy unless-stopped.

    • tty and stdin_open: Enabled for interactive access.

Starting Redis

To deploy Redis using this Docker Compose file, run the following command in the directory containing the file docker-compose.yaml (will work the same on both VPS and your local machine):

docker-compose up -d

This command will start the Redis container in the background (-d) based on the settings specified in the file docker-compose.yaml.

If the container was deployed on a local machine, then “localhost” can be used as the host. Otherwise, like mine, since I deployed the container on a VPS server, use the IP address of the VPS server.

The connection link with login and password will look like this:

redis://username:password@193.3.298.206:6380/0

Pay attention to the link format. It consists of several parts:

  • redis:// – indicate that we are connecting to Redis

  • HOST is either the server's IP address or “localhost” if you ran Redis on a local machine

  • 6380 is the port you set in the docker-compose.yaml file

  • 0 is the database number. By default, Redis has 16 databases (from 0 to 15). The number can be increased via config.

Here is an example of connecting via python (library redis, which can be installed with command pip/pip3 install redis) indicating the connection parameters:

Importing Redis into python:

import redis

Create a Redis object:

r = redis.Redis(host="193.3.298.206", port=6380, db=0, username="username", password='your_pass')

Testing the connection:

try:
    info = r.info()
    print(info['redis_version'])
    response = r.ping()
    if response:
        print("Подключение успешно!")
    else:
        print("Не удалось подключиться к Redis.")
except redis.exceptions.RedisError as e:
    print(f"Ошибка: {e}")

Let's look at the console:

7.2.5
Подключение успешно!

r.ping() sends a command PING to Redis. If Redis responds, the method will return True. We also got the redis version on the server we connected to, which means that everything worked!

Conclusion

Using Docker Compose to deploy Redis greatly simplifies database management while providing great flexibility and reliability. The file described above docker-compose.yaml contains basic settings for running Redis with security, performance, health monitoring, and resource management settings, making it an excellent choice for most projects.

If this information was useful to you, please let me know by liking, commenting or subscribing.

Thank you for attention.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *