2

I want to run a redis container with initial data in it. In the documentation of the image, I can use a volume to mount to /data. My question is: will redis be able to read the data from it and load it? And if so, what should be in the directory that I mount? My (very naive) attempt was to put a file with name "someFile" and hopefully redis will know to save it with key "someFile" and the content of the file as the data. Obviously it didn't work.

Any help would be appreciated.

Guy Smorodinsky
  • 902
  • 7
  • 16

2 Answers2

8

Depending on how large your initial data set is and if your initial data doesn't change much, it may be easier to have your clean docker container load it on startup from a *.redis file using redis-cli (link).

Create your seed commands file (my-data.redis):

SET key1 val1
SET key2 val2
...
...

Create a redis startup shell script (my-redis.sh):

# start server in background and wait for 1 sec
redis-server --daemonize yes && sleep 1 
# slurp all data from file to redis in memory db (note the dir)
redis-cli < /my-dir/my-data.redis 
# persist data to disk
redis-cli save 
# stop background server
redis-cli shutdown 
# start the server normally
redis-server 

Create a custom redis docker image with your shell script as CMD, something like this (a better solution would be to hack the entrypoint but who's got time for that?):

FROM redis:latest
COPY my-data.redis /my-dir/
COPY start-redis.sh /my-dir/
CMD ["sh", "/my-dir/my-redis.sh"]

Done. No external volumes or builder containers needed. Build and run:

docker build -t my-redis:latest .
docker run -p 6379:6379 my-redis:latest
AlexanderF
  • 919
  • 1
  • 13
  • 28
  • Just a reminder. The file containing the data you want to populate doesn't have to be `*.redis`. It can be any format. – SiegeSailor Aug 01 '23 at 20:28
1

You can run the redis container one first time setting an empty directory as the data volume and populate the redis data using the redis CLI. Once you stop the container, the data directory will contain a working redis data set.

If you run another container instance specifying the same directory, redis will use that data.

Please be aware that you will need to configure redis in order to persist data to the filesystem accordingly (check https://redis.io/topics/persistence)

whites11
  • 12,008
  • 3
  • 36
  • 53