Do I still need to set maxmemory if I put a memory limit on the container for Redis server?
Asked Answered
C

1

7

I want to configure Redis as an LRU cache. I'd like to avoid repeating myself for the memory limits. If I do

command: redis-server --maxmemory-policy allkeys-lru 
deploy:
  resources:
    limits:
      memory: 1.5G

would it be enough or do I really need to put in something like this (I used a slightly lower size for the OS etc)

command: redis-server --maxmemory-policy allkeys-lru --maxmemory 1.4G
deploy:
  resources:
    limits:
      memory: 1.5G
Complaisant answered 19/1, 2022 at 21:19 Comment(0)
C
8

Checking the redis-cli info memory it shows the total memory to be the full system size, so likely without maxmemory it will use that value.

However, using getting the memory limit from inside the container and a bit of bash arithmetic, you can create a command that will do the work so the operations only need to tweak one number rather than muck around with the command. And combining with a proper HEALTHCHECK for Redis

services:
 cache:
    image: redis:6
    command:
      - bash
      - -c
      - redis-server --appendonly yes --maxmemory $$(( $$( cat /sys/fs/cgroup/memory/memory.limit_in_bytes 2>/dev/null || cat /sys/fs/cgroup/memory.max ) - 100000000)) --maxmemory-policy volatile-lru
    healthcheck:
      test: [ "CMD", "redis-cli", "--raw", "incr", "ping" ]
    networks:
      - default
    deploy:
      resources:
        limits:
          memory: 512M

This will set the maxmemory to the one defined in the compose file minus 100MB for the overhead.

The two cats in the middle try both CGroupV2 and CGroup V1 locatons for determining the memory limit.

Complaisant answered 20/1, 2022 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.