Il est possible qu'une partie ou l'ensemble des informations de cette page ne s'appliquent pas au Cloud de confiance S3NS. Pour en savoir plus, consultez l'article
Différences par rapport à Google Cloud.
Configurer des instances dupliquées externes
Cette page explique comment configurer une instance Cloud SQL qui réplique les données sur une instance dupliquée externe à Cloud SQL à l'aide de l'
extension pglogical avec
logical decoding
.
Pour en savoir plus sur la réplication, consultez À propos de la réplication dans Cloud SQL.
Définir la configuration de l'instance dupliquée externe
Avant de commencer
Pour effectuer cette tâche, vous devez disposer d'une instance Cloud SQL et d'une instance PostgreSQL externe répondant aux exigences relatives aux instances dupliquées externes.
Exigences concernant l'instance source
L'instance source d'une instance répliquée externe avec accès en lecture doit être une instance principale ou autonome. Vous ne pouvez pas utiliser une instance Cloud SQL dupliquée avec accès en lecture comme instance source pour une instance dupliquée externe avec accès en lecture. Les instances répliquées avec accès en lecture sont parfois recréées à partir du clone de disque de leur instance principale. Leur état de réplication vers une instance répliquée avec accès en lecture externe ne peut pas être conservé par l'instance répliquée avec accès en lecture.
- Accédez à la page Instances Cloud SQL dans la console Trusted Cloud .
- Autorisez l'adresse IP de l'instance dupliquée externe à accéder à l'instance principale.
Pour en savoir plus sur l'activation de l'accès à une adresse IP, consultez la section Configurer l'accès pour les connexions IP.
- Enregistrez l'adresse IP publique et l'adresse IP sortante publique de l'instance principale pour une utilisation ultérieure. Vous pouvez trouver ces valeurs sur la page Présentation de l'instance.
- Cliquez sur l'icône Cloud Shell
dans l'angle supérieur droit.
- Lorsque l'invite Cloud Shell s'affiche, utilisez le client PostgreSQL intégré pour vous connecter à votre instance principale :
gcloud sql connect PRIMARY_INSTANCE_NAME \
--user=postgres
- Saisissez votre mot de passe racine. L'invite postgres doit alors s'afficher.
- Créez un utilisateur PostgreSQL avec l'attribut
REPLICATION
.
CREATE USER REPLICATION_USER WITH REPLICATION IN ROLE cloudsqlsuperuser LOGIN PASSWORD 'REPLICATION_USER_PASSWORD';
- Installez et configurez l'extension pglogical :
Modifiez l'instance Cloud SQL en ajoutant et en définissant les options suivantes :
Redémarrez la base de données, connectez-vous en tant qu'utilisateur replication_user et créez l'extension pglogical
:
CREATE EXTENSION pglogical;
- Créez un nœud pglogical :
Un _nœud_ pglogical représente une instance PostgreSQL physique et stocke les détails de connexion de cette instance.
SELECT pglogical.create_node(
node_name := 'provider',
dsn := 'host=PRIMARY_PUBLIC_IP_ADDRESS port=5432 dbname=DATABASE_NAME user=REPLICATION_USER password=REPLICATION_USER_PASSWORD'
);
- Si vous lancez une nouvelle base de données, créez la même base de données et les mêmes tables sur les instances principale et répliquée. Exemple :
CREATE DATABASE test;
\connect test;
CREATE TABLE replica_test (id SERIAL PRIMARY KEY, data text);
INSERT INTO replica_test (data) VALUES ('apple'), ('banana'), ('cherry');
CREATE EXTENSION pglogical;
- Si vous disposez déjà d'une base de données sur l'instance principale, vous devez la créer sur l'instance dupliquée. Pour ce faire, exportez la base de données de l'instance principale vers un bucket Cloud Storage, puis importez-la dans l'instance dupliquée. Apprenez-en plus sur l'exportation de données de Cloud SQL vers un fichier de vidage SQL dans Cloud Storage.
-
Pour gérer la réplication de différents ensembles de données dans différentes destinations, pglogical utilise le concept d'ensemble de réplication. Par exemple, pour ajouter une table à l'ensemble de réplication par défaut, procédez comme suit :
SELECT pglogical.replication_set_add_table('default', 'replica_test', true);
- Créez un utilisateur spécial pour la réplication et accordez-lui des droits de réplication :
CREATE USER REPLICATION_USER WITH REPLICATION SUPERUSER LOGIN PASSWORD 'REPLICATION_USER_PASSWORD';
- Si vous lancez une nouvelle base de données, utilisez REPLICATION_USER pour créer la même base de données et les mêmes tables sur les instances principale et répliquée. Exemple :
CREATE DATABASE test;
\connect test;
CREATE TABLE replica_test (id SERIAL PRIMARY KEY, data text);
INSERT INTO replica_test (data) VALUES ('apple'), ('banana'), ('cherry');
- Si vous chargez l'instance dupliquée externe avec un fichier exporté à partir de l'instance principale, téléchargez ce fichier à partir de Cloud Storage. Si votre instance dupliquée externe se trouve sur une instance Compute Engine, vous pouvez télécharger le fichier à l'aide de la commande
gcloud storage
:
gcloud storage cp gs://BUCKET_NAME/DUMP_FILE_NAME .
- Importez le fichier dans votre base de données.
psql --user=postgres --password < DUMP_FILE_NAME.
- Installez
pglogical
en fonction de votre système d'exploitation (par exemple, sudo apt-get install postgresql-13-pglogical
sur les systèmes Debian exécutant la version 13 de PostgreSQL).
- Connectez-vous à la base de données en tant qu'utilisateur replication_user, puis définissez les paramètres suivants :
ALTER SYSTEM SET shared_preload_libraries = 'pglogical';
ALTER SYSTEM SET max_replication_slots = #; (where # is the same as you set on the primary).
ALTER SYSTEM SET max_worker_processes = #; (where # is the same as you set on the primary).
# Logout of the database and restart it. For example,
# sudo /etc/init.d/postgresql restart
# Log back in the database as the replication_user.
# Since the pglogical extension is created local to each database, you need to
# execute CREATE EXTENSION pglogical
in each database you create, so if you
# haven't already done that:
CREATE EXTENSION pglogical;
For more information about these flags, see the PostgreSQL resources page.
- Créez un nœud pglogical :
SELECT pglogical.create_node(
node_name := 'subscriber',
dsn := 'host=REPLICA_PUBLIC_IP_ADDRESS port=5432 dbname=DATABASE_NAME user=REPLICATION_USER password=REPLICATION_USER_PASSWORD'
);
- Créez un abonnement pglogical :
SELECT pglogical.create_subscription(
subscription_name := 'SUBSCRIPTION_NAME',
provider_dsn := 'host=PRIMARY_PUBLIC_IP_ADDRESS port=5432 dbname=DATABASE_NAME user=REPLICATION_USER password=REPLICATION_USER_PASSWORD'
);
- Vérifiez l'état de l'abonnement :
SELECT * FROM pglogical.show_subscription_status('SUBSCRIPTION_NAME');
- Si l'état
replicating
s'affiche, le processus de configuration a réussi.
- Insérez des données dans l'instance principale, puis vérifiez qu'elles s'affichent également dans l'instance dupliquée.
Résoudre les problèmes
Consultez la section
Résoudre les problèmes liés à pglogical.
Étapes suivantes
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/03 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/03 (UTC)."],[],[],null,["# Configure external replicas\n\n\u003cbr /\u003e\n\n[MySQL](/sql/docs/mysql/replication/configure-external-replica \"View this page for the MySQL database engine\") \\| PostgreSQL \\| [SQL Server](/sql/docs/sqlserver/replication/configure-external-replica \"View this page for the SQL Server database engine\")\n\n\u003cbr /\u003e\n\nThis page describes how to configure a Cloud SQL instance that replicates to a replica external to Cloud SQL using the [pglogical extension](/sql/docs/postgres/replication/configure-logical-replication) with `logical decoding`.\n\nFor more information about replication, see\n[About replication in Cloud SQL](/sql/docs/postgres/replication).\n\nSet up the external replica configuration\n-----------------------------------------\n\n### Before you begin\n\nBefore you start this task, you must have a Cloud SQL instance and an\nexternal PostgreSQL instance that meets the [requirements for external\nreplicas](/sql/docs/postgres/replication#external-read-replicas).\n\n### Configure the primary instance\n\n1. Go to the [Cloud SQL Instances page](https://console.cloud.google.com/sql/instances) in the Google Cloud console.\n2. Enable access on the primary instance for the IP address of the external replica. For information about enabling IP access, see\n [Configuring access for IP connections](/sql/docs/postgres/configure-ip).\n\n3. Record the public IP address and the public outgoing IP address of the primary instance for later use. You can find these values on the instance's **Overview** page.\n4. Click the Cloud Shell icon in the upper right corner.\n5. At the Cloud Shell prompt, use the built-in PostgreSQL client to connect to your primary instance: \n\n ```bash\n \n gcloud sql connect PRIMARY_INSTANCE_NAME \\\n --user=postgres\n \n \n ```\n6. Enter your root password. You should then see the postgres prompt.\n7. Create a PostgreSQL user with the `REPLICATION` attribute. \n\n CREATE USER \u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e WITH REPLICATION IN ROLE cloudsqlsuperuser LOGIN PASSWORD '\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e';\n \n8. Install and configure the pglogical extension: Edit the Cloud SQL instance to add and set the following flags:\n\n - `cloudsql.enable_pglogical`\n - `cloudsql.logical_decoding`\n - `max_replication_slots`\n - `max_worker_processes`\n - `max_wal_senders`\n - For more information about these flags, see the [PostgreSQL resources](/sql/docs/postgres/replication/configure-logical-replication#postgresql-resources) page.\n\n Restart the database, then login, change to the replication_user,\n create the `pglogical` extension: \n\n ```sql\n CREATE EXTENSION pglogical;\n \n ```\n9. Create a pglogical node:\n A pglogical _node_ represents a physical PostgreSQL instance, and stores\n connection details for that instance.\n\n ```sql\n SELECT pglogical.create_node(\n node_name := 'provider',\n dsn := 'host=\u003cvar translate=\"no\"\u003ePRIMARY_PUBLIC_IP_ADDRESS\u003c/var\u003e port=5432 dbname=\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e user=\u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e password=\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e'\n );\n \n ```\n10. If you are starting with a new database, create the same database and tables on both the primary and replica instances. For example: \n\n ```sql\n CREATE DATABASE test;\n\n \\connect test;\n\n CREATE TABLE replica_test (id SERIAL PRIMARY KEY, data text);\n INSERT INTO replica_test (data) VALUES ('apple'), ('banana'), ('cherry');\n\n CREATE EXTENSION pglogical;\n ```\n11. If you already have a database on the primary instance, you must create the same on the replica. To do this, export the database from the primary instance to a Cloud Storage bucket and import it into the replica. Learn more about [Exporting data from Cloud SQL to a SQL dump file in Cloud Storage](/sql/docs/postgres/import-export/exporting#cloud-sql).\n12. To support replicating different sets of data to different destinations, pglogical has the concept of a replication set. For example, to add a table to the default replication set: \n\n ```sql\n SELECT pglogical.replication_set_add_table('default', 'replica_test', true);\n \n ```\n\n### Configure the external replica\n\n1. Create a special user for replication and grant replication privileges: \n\n CREATE USER \u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e WITH REPLICATION SUPERUSER LOGIN PASSWORD '\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e';\n \n2. If you are starting with a new database, use the \u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e to create the same database and tables on both the primary and replica instances. For example: \n\n ```sql\n CREATE DATABASE test;\n \\connect test;\n CREATE TABLE replica_test (id SERIAL PRIMARY KEY, data text);\n INSERT INTO replica_test (data) VALUES ('apple'), ('banana'), ('cherry');\n \n ```\n3. If you are seeding the external replica instance with a file you exported file from the primary instance, download the exported file from Cloud Storage. If your external replica is on a Compute Engine instance, you can download the file using the `gcloud storage` command: \n\n ```bash\n gcloud storage cp gs://BUCKET_NAME/DUMP_FILE_NAME .\n \n ```\n4. Import the file into your database. \n\n ```\n psql --user=postgres --password \u003c DUMP_FILE_NAME.\n ```\n5. Install `pglogical` according to your OS. For example, on Debian systems running PostgreSQL version 13, `sudo apt-get install postgresql-13-pglogical`.\n6. Login to the database as the replication_user and set the following parameters: \n\n ALTER SYSTEM SET shared_preload_libraries = 'pglogical';\n ALTER SYSTEM SET max_replication_slots = #; (where # is the same as you set on the primary).\n ALTER SYSTEM SET max_worker_processes = #; (where # is the same as you set on the primary).\n # Logout of the database and restart it. For example,\n # sudo /etc/init.d/postgresql restart\n # Log back in the database as the replication_user.\n # Since the pglogical extension is created local to each database, you need to\n # execute CREATE EXTENSION pglogical in each database you create, so if you\n # haven't already done that:\n CREATE EXTENSION pglogical;\n For more information about these flags, see the /sql/docs/postgres/replication/configure-logical-replication#postgresql-resources page.\n \n7. Create a pglogical node: \n\n ```sql\n SELECT pglogical.create_node(\n node_name := 'subscriber',\n dsn := 'host=\u003cvar translate=\"no\"\u003eREPLICA_PUBLIC_IP_ADDRESS\u003c/var\u003e port=5432 dbname=\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e user=\u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e password=\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e'\n );\n \n ```\n8. Create a pglogical subscription: \n\n ```sql\n SELECT pglogical.create_subscription(\n subscription_name := '\u003cvar translate=\"no\"\u003eSUBSCRIPTION_NAME\u003c/var\u003e',\n provider_dsn := 'host=\u003cvar translate=\"no\"\u003ePRIMARY_PUBLIC_IP_ADDRESS\u003c/var\u003e port=5432 dbname=\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e user=\u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e password=\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e'\n );\n \n ```\n9. Check the status of the subscription: \n\n ```sql\n SELECT * FROM pglogical.show_subscription_status('\u003cvar translate=\"no\"\u003eSUBSCRIPTION_NAME\u003c/var\u003e');\n \n ```\n10. If the status appears as `replicating`, then the setup is successful.\n11. Insert some data into the primary and check the replica to make sure the data appears there as well.\n\nTroubleshoot\n------------\n\nSee [Troubleshooting pglogical](/sql/docs/postgres/replication/configure-logical-replication#troubleshooting-pglogical)\n\nWhat's next\n-----------\n\n- Learn how to [manage replicas](/sql/docs/postgres/replication/manage-replicas).\n- Learn about [requirements and best practices for the external replica configuration](/sql/docs/postgres/replication#external-read-replicas).\n- Learn more about [PostgreSQL replication](https://www.postgresql.org/docs/current/static/logical-replication.html).\n- Learn more about [replication configuration settings](https://www.postgresql.org/docs/current/static/runtime-config-replication.html).\n- Learn more about [replicating from an external server](/sql/docs/postgres/replication/replication-from-external)."]]