redis docker - create a container with data

谁说我不能喝 提交于 2019-12-24 19:39:47

问题


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.


回答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)




回答2:


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


来源:https://stackoverflow.com/questions/45279497/redis-docker-create-a-container-with-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!