One place for hosting & domains

      Replication

      How To Set Up Physical Streaming Replication with PostgreSQL 12 on Ubuntu 20.04


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Streaming replication is a popular method you can use to horizontally scale your relational databases. It uses two or more copies of the same database cluster running on separate machines. One database cluster is referred to as the primary and serves both read and write operations; the others, referred to as the replicas, serve only read operations. You can also use streaming replication to provide high availability of a system. If the primary database cluster or server were to unexpectedly fail, the replicas are able to continue serving read operations, or (one of the replicas) become the new primary cluster.

      PostgreSQL is a widely used relational database that supports both logical and physical replication. Logical replication streams high-level changes from the primary database cluster to the replica databases. Using logical replication, you can stream changes to just a single database or table in a database. However, in physical replication, changes to the WAL (Write-Ahead-Logging) log file are streamed and replicated in the replica clusters. As a result, you can’t replicate specific areas of a primary database cluster, but instead all changes to the primary are replicated.

      In this tutorial, you will set up physical streaming replication with PostgreSQL 12 on Ubuntu 20.04 using two separate machines running two separate PostgreSQL 12 clusters. One machine will be the primary and the other, the replica.

      Prerequisites

      To complete this tutorial, you will need the following:

      • Two separate machines Ubuntu 20.04 machines; one referred to as the primary and the other referred to as the replica. You can set these up with our Initial Server Setup Guide, including non-root users with sudo permissions and a firewall.
      • Your firewalls configured to allow HTTP/HTTPS and traffic on port 5432—the default port used by PostgreSQL 12. You can follow How To Set Up a Firewall with ufw on Ubuntu 20.04 to configure these firewall settings.
      • PostgreSQL 12 running on both Ubuntu 20.04 Servers. Follow Step 1 of the How To Install and Use PostgreSQL on Ubuntu 20.04 tutorial that covers the installation and basic usage of PostgreSQL on Ubuntu 20.04.

      Step 1 — Configuring the Primary Database to Accept Connections

      In this first step, you’ll configure the primary database to allow your replica database(s) to connect. By default, PostgreSQL only listens to the localhost (127.0.0.1) for connections. To change this, you’ll first edit the listen_addresses configuration parameter on the primary database.

      On your primary server, run the following command to connect to the PostgreSQL cluster as the default postgres user:

      Once you have connected to the database, you’ll modify the listen_addresses parameter using the ALTER SYSTEM command:

      • ALTER SYSTEM SET listen_addresses TO 'your_replica_IP_addr';

      Replace 'your_replica_IP_addr' with the IP address of your replica machine.

      You will receive the following output:

      Output

      ALTER SYSTEM

      The command you just entered instructs the PostgreSQL database cluster to allow connections only from your replica machine. If you were using more than one replica machine, you would list the IP addresses of all your replicas separated by commas. You could also use '*' to allow connections from all IP addresses, however, this isn’t recommended for security reasons.

      Note: You can also run the command on the database from the terminal using psql -c as follows:

      • sudo -u postgres psql -c "ALTER SYSTEM SET listen_addresses TO 'your_replica_IP_adder';"

      Alternatively, you can change the value for listen_addresses by manually editing the postgresql.conf configuration file, which you can find in the /etc/postgresql/12/main/ directory by default. You can also get the location of the configuration file by running SHOW config_file; on the database cluster.

      To open the file using nano use:

      • sudo nano /etc/postgresql/12/main/postgresql.conf

      Once you’re done, your primary database will now accept connections from other machines. Next, you’ll create a role with the appropriate permissions that the replica will use when connecting to the primary.

      Step 2 — Creating a Special Role with Replication Permissions

      Now, you need to create a role in the primary database that has permission to replicate the database. Your replica will use this role when connecting to the primary. Creating a separate role just for replication also has security benefits. Your replica won’t be able to manipulate any data on the primary; it will only be able to replicate the data.

      To create a role, you need to run the following command on the primary cluster:

      • CREATE ROLE test WITH REPLICATION PASSWORD 'testpassword' LOGIN;

      You’ll receive the following output:

      Output

      CREATE ROLE

      This command creates a role named test with the password 'testpassword', which has permission to replicate the database cluster.

      PostgreSQL has a special replication pseudo-database that the replica connects to, but you first need to edit the /etc/postgresql/12/main/pg_hba.conf configuration file to allow your replica to access it. So, exit the PostgreSQL command prompt by running:

      Now that you’re back at your terminal command prompt, open the /etc/postgresql/12/main/pg_hba.conf configuration file using nano:

      • sudo nano /etc/postgresql/12/main/pg_hba.conf

      Append the following line to the end of the pg_hba.conf file:

      /etc/postgresql/12/main/pg_hba.conf

      . . .
      host    replication     test    your-replica-IP/32   md5
      

      This ensures that your primary allows your replica to connect to the replication pseudo-database using the role, test, you created earlier. The host value means to accept non-local connections via plain or SSL-encrypted TCP/IP sockets. replication is the name of the special pseudo-database that PostgreSQL uses for replication. Finally, the value md5 is the type of authentication used. If you want to have more than one replica, just add the same line again to the end of the file with the IP address of your other replica.

      To ensure these changes to the configuration file are implemented, you need to restart the primary cluster using:

      • sudo systemctl restart postgresql@12-main

      If your primary cluster restarted successfully, it is correctly set up and ready to start streaming once your replica connects. Next, you’ll move on to setting up your replica cluster.

      Step 3 — Backing Up the Primary Cluster on the Replica

      As you are setting up physical replication with PostgreSQL in this tutorial, you need to perform a physical backup of the primary cluster’s data files into the replica’s data directory. To do this, you’ll first clear out all the files in the replica’s data directory. The default data directory for PostgreSQL on Ubuntu is /var/lib/postgresql/12/main/.

      You can also find PostgreSQL’s data directory by running the following command on the replica’s database:

      Once you have the location of the data directory, run the following command to remove everything:

      • sudo -u postgres rm -r /var/lib/postgresql/12/main/*

      Since the default owner of the files in the directory is the postgres user, you will need to run the command as postgres using sudo -u postgres.

      Note:
      If in the exceedingly rare case a file in the directory is corrupted and the command does not work, remove the main directory all together and recreate it with the appropriate permissions as follows:

      • sudo -u postgres rm -r /var/lib/postgresql/12/main
      • sudo -u postgres mkdir /var/lib/postgresql/12/main
      • sudo -u postgres chmod 700 /var/lib/postgresql/12/main

      Now that the replica’s data directory is empty, you can perform a physical backup of the primary’s data files. PostgreSQL conveniently has the utility pg_basebackup that simplifies the process. It even allows you to put the server into standby mode using the -R option.

      Execute the pg_basebackup command on the replica as follows:

      • sudo -u postgres pg_basebackup -h primary-ip-addr -p 5432 -U test -D /var/lib/postgresql/12/main/ -Fp -Xs -R
      • The -h option specifies a non-local host. Here, you need to enter the IP address of your server with the primary cluster.

      • The -p option specifies the port number it connects to on the primary server. By default, PostgreSQL uses port :5432.

      • The -U option allows you to specify the user you connect to the primary cluster as. This is the role you created in the previous step.

      • The -D flag is the output directory of the backup. This is your replica’s data directory that you emptied just before.

      • The -Fp specifies the data to be outputted in the plain format instead of as a tar file.

      • -Xs streams the contents of the WAL log as the backup of the primary is performed.

      • Lastly, -R creates an empty file, named standby.signal, in the replica’s data directory. This file lets your replica cluster know that it should operate as a standby server. The -R option also adds the connection information about the primary server to the postgresql.auto.conf file. This is a special configuration file that is read whenever the regular postgresql.conf file is read, but the values in the .auto file override the values in the regular configuration file.

      When the pg_basebackup command connects to the primary, you will be prompted to enter the password for the role you created in the previous step. Depending on the size of your primary database cluster, it may take some time to copy all the files.

      Your replica will now have all the data files from the primary that it requires to begin replication. Next, you’ll be putting the replica into standby mode and start replicating.

      Step 4 — Restarting and Testing the Clusters

      Now that the primary cluster’s data files have been successfully backed up on the replica, the next step is to restart the replica database cluster to put it into standby mode. To restart the replica database, run the following command:

      • sudo systemctl restart postgresql@12-main

      If your replica cluster restarted in standby mode successfully, it should have already connected to the primary database cluster on your other machine. To check if the replica has connected to the primary and the primary is streaming, connect to the primary database cluster by running:

      Now query the pg_stat_replication table on the primary database cluster as follows:

      • SELECT client_addr, state FROM pg_stat_replication;

      Running this query on the primary cluster will output something similar to the following:

      Output

      client_addr | state ------------------+----------- your_replica_IP | streaming

      If you have similar output, then the primary is correctly streaming to the replica.

      Conclusion

      You now have two Ubuntu 20.04 servers each with a PostgreSQL 12 database cluster running with physical streaming between them. Any changes now made to the primary database cluster will also appear in the replica cluster.

      You can also add more replicas to your setup if your databases need to handle more traffic.

      If you wish to learn more about physical streaming replication including how to set up synchronous replication to ensure zero chance of losing any mission-critical data, you can read the entry in the official PostgreSQL docs.

      You can check out our PostgreSQL topic page for more tutorials and content.



      Source link

      Comment migrer les données Redis avec réplication sur Ubuntu 18.04


      Introduction

      Redis est un magasin de données en mémoire à valeur fondamentale connu pour sa flexibilité, ses performances, son vaste support linguistique et ses fonctions intégrées comme la réplication. La réplication est la pratique consistant à copier régulièrement des données d’une base de données à une autre afin d’avoir une réplique qui reste toujours une copie exacte de l’instance primaire. Une utilisation courante de la réplication de Redis consiste à migrer un magasin de données Redis existant vers un nouveau serveur, comme on peut le faire lorsqu’on augmente la taille de son infrastructure pour obtenir de meilleures performances.

      Ce tutoriel décrit le processus d’utilisation des fonctions de réplication intégrées de Redis pour migrer des données d’un serveur Ubuntu 18.04 (la “source”) vers un autre (la “cible”). Cela implique d’apporter quelques modifications à la configuration de chaque serveur, de définir le serveur cible pour qu’il fonctionne comme une réplique de la source, puis de promouvoir la réplique en tant que primaire une fois la migration terminée.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin de :

      Étape 1 – (Facultatif) Chargement de votre instance Redis source avec des échantillons de données

      Cette étape facultative consiste à charger votre instance de Redis source avec quelques échantillons de données, afin de pouvoir expérimenter la migration des données dans votre instance cible. Si vous avez déjà des données que vous voulez migrer vers votre cible, vous pouvez passer à l’Étape 2 qui vous indiquera comment procéder.

      Pour commencer, connectez-vous au serveur Ubuntu que vous utiliserez comme instance Redis source, en tant que votre utilisateur non root :

      • ssh sammy@source_server_ip

      Exécutez ensuite la commande suivante pour accéder à votre serveur Redis :

      Si vous avez configuré votre serveur Redis pour exiger une authentification par mot de passe, exécutez la commande auth suivie de votre mot de passe Redis :

      • auth source_redis_password

      Ensuite, exécutez les commandes suivantes. Celles-ci créeront un certain nombre de clés contenant quelques chaînes, un hachage, une liste et un ensemble :

      • mset string1 "Redis" string2 "is" string3 "fun!"
      • hmset hash1 field1 "Redis" field2 "is" field3 "fast!"
      • rpush list1 "Redis" "is" "feature-rich!"
      • sadd set1 "Redis" "is" "free!"

      En outre, exécutez les commandes expire suivantes pour donner un délai d’attente à certaines de ces clés. Cela les rendra volatiles, ce qui signifie que Redis les supprimera après un laps de temps déterminé (7500 secondes dans ce cas) :

      • expire string2 7500
      • expire hash1 7500
      • expire set1 7500

      Avec cela, vous disposez de quelques exemples de données que vous pouvez exporter vers votre instance Redis cible. Gardez l’invite redis-cli ouverte pour l’instant, puisque nous allons exécuter quelques commandes supplémentaires à l’étape suivante pour sauvegarder ces données.

      Étape 2 — Sauvegarde de votre instance Redis source

      Chaque fois que vous envisagez de transférer des données d’un serveur à un autre, il y a un risque que quelque chose tourne mal et vous pourriez perdre des données en conséquence. Même si ce risque est faible, nous utiliserons la commande bgsave de Redis pour créer une sauvegarde de votre base de données source Redis au cas où vous rencontreriez une erreur lors du processus de réplication.

      Si vous ne l’avez pas encore ouvert, commencez par ouvrir l’interface de ligne de commande Redis :

      Si vous avez configuré votre serveur Redis pour exiger une authentification par mot de passe, exécutez la commande auth suivie de votre mot de passe Redis :

      Ensuite, exécutez la commande bgsave. Cela permettra de créer un instantané de votre ensemble de données actuel et de l’exporter vers un fichier dump se trouvant dans le répertoire de travail de Redis :

      Remarque : vous pouvez prendre un instantané de votre base de données Redis avec les commandes save ou bgsave. La raison pour laquelle nous utilisons la commande bgsave ici, cependant, est que la commande save fonctionne de manière synchrone, ce qui signifie qu’elle bloquera tout autre client connecté à la base de données. Pour cette raison, la documentation de la commande save recommande de ne presque jamais l’exécuter dans un environnement de production.

      Au lieu de cela, elle suggère d’utiliser la commande bgsave qui fonctionne de manière asynchrone. Cela amènera Redis à diviser la base de données en deux processus : le processus parent continuera à servir les clients tandis que l’enfant enregistrera la base de données avant de quitter :

      Notez que si les clients ajoutent ou modifient des données pendant que l’opération bgsave est en cours d’exécution, ces modifications ne seront pas prises en compte dans l’instantané.

      Après cela, vous pouvez fermer la connexion à votre instance Redis en exécutant la commande exit.

      Si vous en avez besoin à l’avenir, vous pouvez trouver le fichier dump de données dans le répertoire de travail de votre instance Redis. Rappelez-vous : dans le tutoriel prérequis d’installation de Redis, vous avez configuré votre instance de Redis pour utiliser /var/lib/redis comme répertoire de travail.

      Listez le contenu de votre répertoire de travail Redis pour confirmer qu’il contient le fichier dump des données :

      Si le fichier dump a été exporté correctement, vous le verrez dans la sortie de cette commande. Par défaut, ce fichier est nommé dump.rdb: :

      Output

      dump.rdb

      Après avoir confirmé que vos données ont été sauvegardées correctement, vous êtes prêt à configurer votre serveur Redis source pour accepter les connexions externes et autoriser la réplication.

      Étape 3 — Configuration de votre instance Redis source

      Par défaut, Redis n’est pas configuré pour écouter les connexions externes, ce qui signifie que les répliques que vous configurez ne pourront pas se synchroniser avec votre instance source, à moins que vous ne mettiez à jour sa configuration. Ici, nous allons mettre à jour le fichier de configuration de l’instance source pour permettre les connexions externes et également définir un mot de passe que l’instance cible utilisera pour s’authentifier une fois la réplication commencée. Après cela, nous ajouterons une règle de pare-feu pour autoriser les connexions au port sur lequel Redis fonctionne.

      Ouvrez le fichier de configuration de votre instance Redis source avec votre éditeur de texte préféré. Ici, nous utiliserons nano :

      • sudo nano /etc/redis/redis.conf

      Naviguez vers la ligne qui commence par la directive bind. Par défaut, cela ressemblera à ceci :

      /etc/redis/redis.conf

      . . .
      bind 127.0.0.1
      . . .
      

      Cette directive lie Redis à 127.0.0.1, une adresse de loopback IPv4 qui représente le localhost. Cela signifie que cette instance Redis est configurée pour n’écouter que les connexions qui proviennent du même serveur que celui où elle est installée. Pour autoriser votre instance source à accepter toute connexion effectuée à son adresse IP publique, par exemple celle faite à partir de votre instance cible, ajoutez l’adresse IP de votre serveur Redis source après le 127.0.0.1. Notez que vous ne devez inclure aucune virgule après 127.0.0.1 :

      /etc/redis/redis.conf

      . . .
      bind 127.0.0.1 source_server_IP
      . . .
      

      Ensuite, si vous ne l’avez pas encore fait, utilisez la directive requirepass pour configurer un mot de passe que les utilisateurs doivent entrer avant de pouvoir interagir avec les données sur l’instance source. Pour ce faire, il convient de décommenter la directive et de lui attribuer un mot de passe ou une phrase de passe complexe :

      /etc/redis/redis.conf

      . . .
      requirepass source_redis_password
      . . .
      

      Veillez à noter le mot de passe que vous avez défini ici, car vous en aurez besoin lorsque vous configurez le serveur cible.

      Après ce changement, vous pouvez enregistrer et fermer le fichier de configuration Redis. Si vous l’avez édité avec nano, faites-le en appuyant sur CTRL+X, Y, puis ENTER.

      Ensuite, redémarrez le service Redis pour mettre ces modifications en œuvre :

      • sudo systemctl restart redis

      C’est tout ce que vous devez faire en termes de configuration de Redis, mais si vous avez configuré un pare-feu sur votre serveur, il continuera à bloquer toute tentative de connexion de votre serveur cible avec la source. En supposant que vous avez configuré votre pare-feu avec ufw, vous pourriez le mettre à jour pour autoriser les connexions au port sur lequel Redis fonctionne avec la commande suivante. Notez que Redis est configuré pour utiliser le port 6379 par défaut :

      Une fois ce dernier changement apporté, vous avez terminé de configurer votre serveur Redis source. Continuez à configurer votre instance Redis cible pour qu’elle fonctionne comme une réplique de la source.

      Étape 4 — Configuration de votre instance Redis cible

      À ce stade, vous avez configuré votre instance Redis source pour qu’elle accepte les connexions externes. Cependant, comme vous avez bloqué l’accès à la source en décommentant la directive requirepass, votre instance cible ne pourra pas reproduire les données contenues dans la source. Ici, vous allez configurer votre instance Redis cible pour qu’elle puisse authentifier sa connexion à la source, permettant ainsi la réplication.

      Commencez par vous connecter à votre serveur Redis cible en tant qu’utilisateur non root :

      • ssh sammy@target_server_ip

      Ensuite, ouvrez le fichier de configuration Redis de votre serveur cible :

      • sudo nano /etc/redis/redis.conf

      Si vous ne l’avez pas encore fait, vous devez configurer un mot de passe pour votre instance Redis cible avec la directive requirepass :

      /etc/redis/redis.conf

      . . .
      requirepass target_redis_password
      . . .
      

      Ensuite, décommentez la directive masterauth et attribuez-lui le mot de passe d’authentification de votre instance Redis source. Ce faisant, votre serveur cible sera en mesure de s’authentifier auprès de l’instance source une fois que vous aurez activé la réplication :

      /etc/redis/redis.conf

      . . .
      masterauth source_redis_password
      . . .
      

      Enfin, si vos clients écrivent des informations à votre instance source, vous voudrez les configurer pour qu’ils écrivent également des données à votre instance cible. De cette façon, si un client écrit des données une fois que vous avez redonné à la cible son statut d’instance primaire, elles ne seront pas perdues.

      Pour ce faire, cependant, vous devrez ajuster la directive replica-read-only. La valeur par défaut est yes, ce qui signifie qu’elle est configurée pour devenir une réplique “ en lecture seule ” sur laquelle les clients ne pourront pas écrire. Définissez cette directive sur no pour autoriser les clients à y écrire :

      /etc/redis/redis.conf

      . . .
      replica-read-only no
      . . .
      

      Ce sont là toutes les modifications que vous devez apporter au fichier de configuration de la cible, vous pouvez donc l’enregistrer et le fermer.

      Ensuite, redémarrez le service Redis pour mettre ces modifications en œuvre :

      • sudo systemctl restart redis

      Après avoir redémarré le service Redis, votre serveur cible sera prêt à devenir une réplique de la source. Tout ce que vous devrez faire pour cela, c’est exécuter une seule commande, ce que nous allons faire sous peu.

      Remarque : si certains clients écrivent des données sur votre instance Redis source, c’est le moment de les configurer pour qu’ils écrivent également des données sur votre cible.

      Étape 5 — Démarrage et vérification de la réplication

      À ce stade, vous avez configuré votre instance Redis source pour qu’elle accepte les connexions de votre serveur cible et vous avez configuré votre instance Redis cible pour qu’elle puisse s’authentifier à la source en tant que réplique. Une fois ces pièces en place, vous êtes prêt à transformer votre instance cible en une réplique de la source.

      Commencez par ouvrir l’interface de ligne de commande Redis sur votre serveur Redis cible :

      Exécutez la commande auth pour authentifier la connexion :

      Ensuite, transformez l’instance cible en une réplique de la source avec la commande replicaof Veillez à remplacer source_server_ip par l’adresse IP publique de votre instance source et source_port par le port utilisé par Redis sur votre instance source :

      • replicaof source_server_ip source_port

      À partir de l’invite, exécutez la commande scan suivante. Cela va retourner toutes les clés actuellement détenues par la réplique :

      Si la réplication fonctionne comme prévu, vous verrez toutes les clés de votre instance source détenues dans la réplique. Si vous avez chargé votre source avec les données de l’échantillon à l’Étape 1, la sortie de la commande scan ressemblera à ceci :

      Output

      1) "0" 2) 1) "string3" 2) "string1" 3) "set1" 4) "string2" 5) "hash1" 6) "list1"

      Remarque : il faut savoir que cette commande peut retourner les clés dans un ordre différent de celui qui est indiqué dans cet exemple.

      Cependant, si cette commande ne renvoie pas les mêmes clés que celles de votre instance Redis source, il se peut qu’une erreur dans les fichiers de configuration d’un de vos serveurs empêche la base de données cible de se connecter à la source. Dans ce cas, fermez la connexion à votre instance Redis cible, et vérifiez que vous avez correctement édité les fichiers de configuration sur vos serveurs Redis source et cible.

      Tant que la connexion est ouverte, vous pouvez également confirmer que les clés que vous avez définies pour expire sont toujours volatiles. Pour ce faire, exécutez la commande ttl avec une de ces clés comme argument :

      Cela va retourner le nombre de secondes avant que cette clé ne soit supprimée :

      Output

      5430

      Une fois que vous avez confirmé que les données de votre instance source ont été correctement synchronisées avec votre cible, vous pouvez faire en sorte que la cible redevienne une instance primaire en exécutant une nouvelle fois la commande replicof. Cette fois, cependant, au lieu de suivre replicaof avec une adresse IP et un port, suivez-la avec no one. L’instance cible cessera alors immédiatement de se synchroniser avec la source :

      Pour confirmer que les données reproduites à partir de la source persistent sur la cible, exécutez à nouveau la commande scan que vous avez saisie précédemment :

      scan 0
      

      Vous devriez voir les mêmes clés dans la sortie de cette commande que lorsque vous avez exécuté la commande scan pendant que la cible répliquait encore la source :

      Output

      1) "0" 2) 1) "string3" 2) "string1" 3) "set1" 4) "string2" 5) "hash1" 6) "list1"

      Vous avez ainsi réussi à migrer toutes les données de votre instance Redis source vers votre cible. Si vous avez des clients qui écrivent encore des données sur l’instance source, c’est le moment de les configurer pour qu’ils n’écrivent que sur la cible.

      Conclusion

      Outre la réplication, il existe plusieurs méthodes que vous pouvez utiliser pour migrer des données d’une instance Redis à une autre, mais la réplication présente l’avantage de nécessiter relativement peu de changements de configuration pour fonctionner et une seule commande pour la lancer ou l’arrêter.

      Si vous souhaitez en savoir plus sur le travail avec Redis, nous vous encourageons à consulter notre série tutoriel sur Comment gérer une base de données Redis. Par ailleurs, si vous souhaitez transférer vos données Redis vers une instance Redis gérée par DigitalOcean, suivez notre guide sur la façon de procéder.



      Source link

      How To Migrate Redis Data with Replication on Ubuntu 18.04


      Introduction

      Redis is an in-memory, key-value data store known for its flexibility, performance, wide language support, and built-in features like replication. Replication is the practice of regularly copying data from one database to another in order to have a replica that always remains an exact duplicate of the primary instance. One common use of Redis replication is to migrate an existing Redis data store to a new server, as one might do when scaling up their infrastructure for better performance.

      This tutorial outlines the process of using Redis’s built-in replication features to migrate data from one Ubuntu 18.04 server (the “source”) to another (the “target”). This involves making a few configuration changes to each server, setting the target server to function as a replica of the source, and then promoting the replica back to a primary after the migration is completed.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — (Optional) Loading Your Source Redis Instance with Sample Data

      This optional step involves loading your source Redis instance with some sample data so you can experiment with migrating data to your target instance. If you already have data that you want to migrate over to your target, you can move ahead to Step 2 which will go over how to back it up.

      To begin, connect to the Ubuntu server you’ll use as your source Redis instance as your non-root user:

      • ssh sammy@source_server_ip

      Then run the following command to access your Redis server:

      If you’ve configured your Redis server to require password authentication, run the auth command followed by your Redis password:

      • auth source_redis_password

      Next, run the following commands. These will create a number of keys holding a few strings, a hash, a list, and a set:

      • mset string1 "Redis" string2 "is" string3 "fun!"
      • hmset hash1 field1 "Redis" field2 "is" field3 "fast!"
      • rpush list1 "Redis" "is" "feature-rich!"
      • sadd set1 "Redis" "is" "free!"

      Additionally, run the following expire commands to provide a few of these keys with a timeout. This will make them volatile, meaning that Redis will delete them after a specified amount of time (7500 seconds, in this case):

      • expire string2 7500
      • expire hash1 7500
      • expire set1 7500

      With that, you have some example data you can export to your target Redis instance. Keep the redis-cli prompt open for now, since we will run a few more commands from it in the next step to back this data up.

      Step 2 — Backing Up Your Source Redis Instance

      Any time you plan to move data from one server to another, there’s a risk that something could go wrong and you could lose data as a result. Even though this risk is small, we will use Redis’s bgsave command to create a backup of your source Redis database in case you encounter an error during the replication process.

      If you don’t already have it open, start by opening up the Redis command line interface:

      Also, if you’ve configured your Redis server to require password authentication, run the auth command followed by your Redis password:

      Next, run the bgsave command. This will create a snapshot of your current data set and export it to a dump file held in Redis’s working directory:

      Note: You can take a snapshot of your Redis database with either the save or bgsave commands. The reason we use the bgsave command here, though, is that the save command runs synchronously, meaning it will block any other clients connected to the database. Because of this, the save command documentation recommends that you should almost never run it in a production environment.

      Instead, it suggests using the bgsave command which runs asynchronously. This will cause Redis to fork the database into two processes: the parent process will continue to serve clients while the child saves the database before exiting:

      Note that if clients add or modify data while the bgsave operation is running, these changes won’t be captured in the snapshot.

      Following that, you can close the connection to your Redis instance by running the exit command:

      If you need it in the future, you can find the data dump file in your Redis instance’s working directory. Recall how in the prerequisite Redis installation tutorial you set your Redis instance to use /var/lib/redis as its working directory.

      List the contents of your Redis working directory to confirm that it’s holding the data dump file:

      If the dump file was exported correctly, you will see it in this command’s output. By default, this file is named dump.rdb:

      Output

      dump.rdb

      After confirming that your data was backed up correctly, you’re all set to configure your source Redis server to accept external connections and allow for replication.

      Step 3 — Configuring Your Source Redis Instance

      By default, Redis isn’t configured to listen for external connections, meaning that any replicas you configure won’t be able to sync with your source instance unless you update its configuration. Here, we will update the source instance’s configuration file to allow for external connections and also set a password which the target instance will use to authenticate once replication begins. After that, we’ll add a firewall rule to allow connections to the port on which Redis is running.

      Open up your source Redis instance’s configuration file with your preferred text editor. Here, we’ll use nano:

      • sudo nano /etc/redis/redis.conf

      Navigate to the line that begins with the bind directive. It will look like this by default:

      /etc/redis/redis.conf

      . . .
      bind 127.0.0.1
      . . .
      

      This directive binds Redis to 127.0.0.1, an IPv4 loopback address that represents localhost. This means that this Redis instance is configured to only listen for connections that originate from the same server as the one where it’s installed. To allow your source instance to accept any connection made to its public IP address, such as those made from your target instance, add your source Redis server’s IP address after the 127.0.0.1. Note that you shouldn’t include any commas after 127.0.0.1:

      /etc/redis/redis.conf

      . . .
      bind 127.0.0.1 source_server_IP
      . . .
      

      Next, if you haven’t already done so, use the requirepass directive to configure a password which users must enter before they can interact with the data on the source instance. Do so by uncommenting the directive and setting it to a complex password or passphrase:

      /etc/redis/redis.conf

      . . .
      requirepass source_redis_password
      . . .
      

      Be sure to take note of the password you set here, as you will need it when you configure the target server.

      Following that change, you can save and close the Redis configuration file. If you edited it with nano, do so by pressing CTRL+X, Y, then ENTER.

      Then, restart the Redis service to put these changes into effect:

      • sudo systemctl restart redis

      That’s all you need to do in terms of configuring Redis, but if you configured a firewall on your server it will continue to block any attempts by your target server to connect with the source. Assuming you configured your firewall with ufw, you could update it to allow connections to the port on which Redis is running with the following command. Note that Redis is configured to use port 6379 by default:

      After making that final change you’re all done configuring your source Redis server. Continue on to configure your target Redis instance to function as a replica of the source.

      Step 4 — Configuring your Target Redis Instance

      By this point you’ve configured your source Redis instance to accept external connections. However, because you’ve locked down access to the source by uncommenting the requirepass directive, your target instance won’t be able to replicate the data held on the source. Here, you will configure your target Redis instance to be able to authenticate its connection to the source, thereby allowing replication.

      Begin by connecting to your target Redis server as your non-root user:

      • ssh sammy@target_server_ip

      Next, open up your target server’s Redis configuration file:

      • sudo nano /etc/redis/redis.conf

      If you haven’t done so already, you should configure a password for your target Redis instance with the requirepass directive:

      /etc/redis/redis.conf

      . . .
      requirepass target_redis_password
      . . .
      

      Next, uncomment the masterauth directive and set it to your source Redis instance’s authentication password. By doing this, your target server will be able to authenticate to the source instance after you enable replication:

      /etc/redis/redis.conf

      . . .
      masterauth source_redis_password
      . . .
      

      Lastly, if you have clients writing information to your source instance, you will want to configure them to write data to your target instance as well. This way, if a client writes any data after you promote the target back to being a primary instance, it won’t get lost.

      To do this, though, you will need to adjust the replica-read-only directive. This is set to yes by default, which means that it’s configured to become a “read-only” replica which clients won’t be able to write to. Set this directive to no to allow clients to write to it:

      /etc/redis/redis.conf

      . . .
      replica-read-only no
      . . .
      

      Those are all the changes you need to make to the target’s configuration file, so you can save and close it.

      Then, restart the Redis service to put these changes into effect:

      • sudo systemctl restart redis

      After restarting the Redis service your target server will be ready to become a replica of the source. All you’ll need to do to turn it into one is to run a single command, which we’ll do shortly.

      Note: If you have any clients writing data to your source Redis instance, now would be a good time to configure them to also write data to your target.

      Step 5 — Starting and Verifying Replication

      By this point, you have configured your source Redis instance to accept connections from your target server and you’ve configured your target Redis instance to be able to authenticate to the source as a replica. With these pieces in place, you’re ready to turn your target instance into a replica of the source.

      Begin by opening up the Redis command line interface on your target Redis server:

      Run the auth command to authenticate the connection:

      Next, turn the target instance into a replica of the source with the replicaof command. Be sure to replace source_server_ip with your source instance’s public IP address and source_port with the port used by Redis on your source instance:

      • replicaof source_server_ip source_port

      From the prompt, run the following scan command. This will return all the keys currently held by the replica:

      If replication is working as expected, you will see all the keys from your source instance held in the replica. If you loaded your source with the sample data in Step 1, the scan command’s output will look like this:

      Output

      1) "0" 2) 1) "string3" 2) "string1" 3) "set1" 4) "string2" 5) "hash1" 6) "list1"

      Note: Be aware that this command may return the keys in a different order than what’s shown in this example.

      However, if this command doesn’t return the same keys held on your source Redis instance, it may be that there is an error in one of your servers’ configuration files preventing the target database from connecting to the source. In this case, close the connection to your target Redis instance, and double check that you’ve edited the configuration files on both your source and target Redis servers correctly.

      While you have the connection open, you can also confirm that the keys you set to expire are still volatile. Do so by running the ttl command with one of these keys as an argument:

      This will return the number of seconds before this key will be deleted:

      Output

      5430

      Once you’ve confirmed that the data on your source instance was correctly synced to your target, you can promote the target back to being a primary instance by running the replicaof command once again. This time, however, instead of following replicaof with an IP address and port, follow it with no one. This will cause the target instance to stop syncing with the source immediately:

      To confirm that the data replicated from the source persist on the target, rerun the scan command you entered previously:

      scan 0
      

      You should see the same keys in this command’s output as when you ran the scan command when the target was still replicating the source:

      Output

      1) "0" 2) 1) "string3" 2) "string1" 3) "set1" 4) "string2" 5) "hash1" 6) "list1"

      With that, you’ve successfully migrated all the data from your source Redis instance to your target. If you have any clients that are still writing data to the source instance, now would be a good time to configure them to only write to the target.

      Conclusion

      There are several methods besides replication you can use to migrate data from one Redis instance to another, but replication has the advantages of requiring relatively few configuration changes to work and only a single command to initiate or stop.

      If you’d like to learn more about working with Redis, we encourage you to check out our tutorial series on How To Manage a Redis Database. Also, if you want to move your Redis data to a Redis instance managed by DigitalOcean, follow our guide on how to do so.



      Source link