create a master and a slave redis container : docker-compose.yml
version: '3.7' services: redis-master: image: redis container_name: redis-master volumes: - "./datamaster:/data" redis-slave: image: redis container_name: redis-slave command: redis-server --slaveof redis-master 6379 volumes: - "./dataslave:/data"
write data on master and read on slave
# start redis docker compose up -d # set a value on master docker exec -ti redismaster redis-cli set a 1 # get a value on slave (shows "1") docker exec -ti redisslave redis-cli get a
when you run "info replication" on a redis slave it returns master_link_status: up and master_sync_in_progress: 0 when it is fully synced.
So you can wait for the save to be in sync with this coimmand
function waitslavesync { echo waitslavesync $1; while true ; do output=$(docker exec -ti $1 redis-cli info replication) link_status=$(echo "$output" | grep -oP '(?<=master_link_status:)[^[:space:]]+') sync_progress=$(echo "$output" | grep -oP '(?<=master_sync_in_progress:)[^[:space:]]+') if [ "$link_status" = "up" ] && [ "$sync_progress" = "0" ]; then echo "$1 is in sync" break; else sleep 1; fi done } waitslavesync redisslave
i can kill a slave and restart it and it has the updated data
docker rm -f redisslave docker compose up -d waitslavesync redisslave docker exec -ti redisslave redis-cli get a
i can kill the master and the slave still has the data. But you cannot write on the slave
if i kill the master the data is gone.
to keep the data i need to activate persistence (run bgsave) and add a volume like ./master:/data
or you can restart the master and make it a slave.
docker rm -f redis-master docker exec -ti redis-slave redis-cli slaveof no one docker compose up -d redis-master docker exec -ti redis-master redis-cli slaveof redis-slave 6379 waitslavesync redis-master
now you can write on the slave. and data is available on master and on slave.
no data have been lost