Auf dieser Seite wird beschrieben, wie Sie eine Cloud SQL-Instanz konfigurieren, die auf Replikate außerhalb von Cloud SQL repliziert werden kann. Außerdem wird erläutert, wie Sie die primäre Instanz in einer Konfiguration externer Replikate zurückstufen, um die Konfiguration umzukehren.
Bevor Sie mit dieser Aufgabe starten, sollten Sie eine Cloud SQL-Instanz und eine externe MySQL-Instanz haben, die die Anforderungen für externe Replikate erfüllen.
Notieren Sie sich die öffentliche IP-Adresse und die öffentliche ausgehende IP-Adresse der primären Instanz zur späteren Verwendung. Sie finden diese Werte auf der Seite Übersicht der Instanz.
Klicken Sie rechts oben auf das Cloud Shell-Symbol ().
Stellen Sie über die Cloud Shell-Eingabeaufforderung mit dem integrierten MySQL-Client eine Verbindung zur primären Instanz her:
Wenn Sie mit einer neuen Datenbank beginnen, erstellen Sie dieselbe Datenbank und dieselben Tabellen sowohl auf der primären Instanz als auch auf der Replikatinstanz. Beispiel:
Wenn auf der primären Instanz bereits eine Datenbank vorhanden ist, müssen Sie dieselbe auf dem Replikat erstellen. Exportieren Sie dazu die Datenbank aus der primären Instanz in einen Cloud Storage-Bucket und importieren Sie sie in das Replikat. Daten aus Cloud SQL in eine SQL-Dumpdatei in Cloud Storage exportieren.
Externes Replikat konfigurieren
Warnung: Bei diesem Vorgang werden alle Daten, einschließlich Nutzer und Passwörter, die in einer MySQL-Datenbank auf dem Replikat gehostet werden, mit den Einstellungen und Daten aus der primären Instanz überschrieben.
Siedeln Sie die neue externe MySQL-Instanz mit der Exportdatei, die Sie aus der primären Instanz erstellt haben, auf der Maschine an, die das Replikat hostet.
Der folgende Befehl lädt beispielsweise eine exportierte Datei mit dem Namen mydump.sql:
mysql --user=root --password < mydump.sql
Bestimmen Sie die Server-ID für dieses Paar aus Replikat und primärer Instanz.
Die Server-ID ist ein numerischer Wert (z. B. "3"), der in der gesamten Konfiguration von externen Replikaten einmalig sein muss, das heißt, jedes Replikat muss eine einmalige Server-ID haben.
Fügen Sie der Optionsdatei my.cnf des Replikats die folgenden Optionen hinzu:
Starten Sie den Prozess mysqld neu, damit die Konfigurationsdatei gelesen werden kann.
Geben Sie in einem mysql-Client auf dem Replikat den folgenden Befehl ein:
CHANGE MASTER TO MASTER_HOST='MASTER_IP_ADDRESS', MASTER_USER='REPLICATION_USER',
MASTER_PASSWORD='REPLICATION_PASSWORD', MASTER_AUTO_POSITION=1;
Starten Sie die Replikation auf dem Replikat:
START SLAVE;
Bestätigen Sie den Replikationsstatus:
SHOW SLAVE STATUS\G;
Wenn "Waiting for master to send event" angezeigt wird, funktioniert die Replikation.
Primäre Instanz eines externen Replikats zurückstufen
Wenn Sie eine Cloud SQL-Instanz mit einem externen Replikat haben, können Sie die Konfiguration umkehren. Dabei ändert sich Folgendes:
Das externe Replikat wird zur neuen primären Instanz.
Die Cloud SQL-Instanz wird zu einem Lesereplikat, das von dem Server repliziert wird, der zuvor das externe Replikat war und jetzt zum Quelldatenbankserver wird
So kehren Sie die Konfiguration externer Replikate um:
Verwenden Sie die Region, in der das Cloud SQL-Replikat gespeichert werden soll.
Starten Sie den Rückstufungsprozess.
Da Sie für diesen API-Aufruf vertrauliche Informationen angeben müssen, sollten Sie die Daten für cURL nicht in der Befehlszeile eingeben, sondern eine JSON-Datei verwenden.
Weitere Informationen zu den Optionen für SSL/TLS finden Sie unter SSL/TLS-Optionen.
Weitere Informationen zu den vom Objekt replicaConfiguration verwendeten Attributen finden Sie unter Von externem Server replizieren.
Warten Sie, bis das externe Replikat alle ausstehenden Transaktionen von der primären Instanz abgeschlossen hat.
Wenn das Replikat aktuell ist, zeigt der Befehl SHOW SLAVE STATUS für Seconds Behind Master 0 an und der Wert Executed_Gtid_Set ist für das externe Replikat und die primäre Cloud SQL-Instanz identisch.
Verwenden Sie den mysql-Client, um die Replikation für das externe Replikat zu beenden:
STOP SLAVE
RESET SLAVE ALL
Warten Sie, bis die Cloud SQL-Instanz mit der Replikation vom externen Server aus begonnen hat, der nun der Quelldatenbankserver ist.
Bei Ausführung des Befehls SHOW SLAVE STATUS für die Cloud SQL-Instanz wird der Replikationsstatus angegeben.
Wenn die Cloud SQL-Instanz erfolgreich vom Quelldatenbankserver repliziert wird, setzen Sie das Flag read_only für den Quelldatenbankserver auf off und aktualisieren Sie Ihre Anwendungen so, dass sie auf den Quelldatenbankserver zeigen.
Fehlerbehebung
Problem
Fehlerbehebung
Fehlermeldung: The slave is connecting ... master has purged
binary logs containing GTIDs that the slave requires.
Die primäre Cloud SQL-Instanz umfasst automatische Sicherungen und binäre Logs. Außerdem wird die Wiederherstellung zu einem bestimmten Zeitpunkt aktiviert. Sie sollte deshalb genügend Logs haben, damit das Replikat aufholen kann. In diesem Fall weiß das Replikat jedoch nicht, ab welcher Zeile mit dem Lesen begonnen werden soll, obwohl die Binärlogs vorhanden sind.
Erstellen Sie eine neue Dumpdatei mit den richtigen Flag-Einstellungen und konfigurieren Sie das externe Replikat mithilfe dieser Datei.
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-09-03 (UTC)."],[],[],null,["# Configure external replicas\n\n\u003cbr /\u003e\n\nMySQL \\| [PostgreSQL](/sql/docs/postgres/replication/configure-external-replica \"View this page for the PostgreSQL database engine\") \\| [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 one or more replicas external to Cloud SQL, and how to demote the primary instance in an external replica configuration to reverse the configuration.\n\nFor more information about replication, see\n[About replication in Cloud SQL](/sql/docs/mysql/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 MySQL instance that meets the [requirements for external\nreplicas](/sql/docs/mysql/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/mysql/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 MySQL client to connect to your primary instance: \n\n ```bash\n \n gcloud sql connect PRIMARY_INSTANCE_NAME \\\n --user=root\n \n \n ```\n6. Enter your root password. You should then see the mysql prompt.\n7. Create a special user for replication and grant replication privileges: \n\n ```bash\n CREATE USER '\u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e'@'%' IDENTIFIED BY '\u003cvar translate=\"no\"\u003eREPLICATION_USER_PASSWORD\u003c/var\u003e';\n GRANT REPLICATION SLAVE ON *.* TO '\u003cvar translate=\"no\"\u003eREPLICATION_USER\u003c/var\u003e'@'%';\n \n ```\n8. 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 USE test;\n\n CREATE TABLE replica_test (id SERIAL PRIMARY KEY, data text);\n INSERT INTO replica_test (data) VALUES ('apple'), ('banana'), ('cherry');\n ```\n9. 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/mysql/import-export/exporting#cloud-sql).\n\n### Configure the external replica\n\nWarning: This procedure overwrites any data hosted in a MySQL database on the replica, including users and passwords, with the settings and data from the primary instance.\n\n1. On the machine hosting the replica, seed your new external MySQL instance with the export file you created from the primary instance. For example, the following command loads an exported file named\n `mydump.sql`:\n\n ```\n mysql --user=root --password \u003c mydump.sql\n ```\n2. Determine the server ID for this replica-primary pair. The server ID is a numeric value (for example, \"3\") that must be unique\n across the external replica configuration\n (each replica must have a unique server ID).\n\n3. Add the following options to the replica's `my.cnf` option file: \n\n ```\n [mysqld]\n server-id=[SERVER_ID]\n gtid_mode=ON\n enforce_gtid_consistency=ON\n log_slave_updates=ON\n replicate-ignore-db=mysql\n binlog-format=ROW\n log_bin=mysql-bin\n expire_logs_days=1\n read_only=ON\n ```\n | **Note:** You must set `gtid_mode=ON` for all external replicas in a configuration that includes a Cloud SQL primary instance. Changing the default to `gtid_mode=OFF` causes replication with the external server to fail.\n\n For more information about MySQL replication options, see\n [Replication and Binary Logging Options](https://dev.mysql.com/doc/refman/8.0/en/replication-options.html).\n4. Restart the `mysqld` process to cause the configuration file to be read.\n5. In a `mysql` client on the replica, enter the following command: \n\n ```\n CHANGE MASTER TO MASTER_HOST='MASTER_IP_ADDRESS', MASTER_USER='REPLICATION_USER',\n MASTER_PASSWORD='REPLICATION_PASSWORD', MASTER_AUTO_POSITION=1;\n ```\n6. Start replication on the replica: \n\n ```\n START SLAVE;\n ```\n7. Confirm replication status:\n\n ```\n SHOW SLAVE STATUS\\G;\n ```\n\n If you see \"Waiting for master to send event\", replication is working.\n\nDemote the primary instance of an external replica\n--------------------------------------------------\n\nWhen you have a Cloud SQL instance with an external replica, you can\nreverse the configuration, which causes these changes to happen:\n\n- The external replica becomes the new primary instance.\n- The Cloud SQL instance becomes a read replica, replicating from the server that was previously the external replica (now called the source database server).\n\nTo reverse the external replica configuration:\n\n1. Create a\n [source representation instance](/sql/docs/mysql/replication/external-server#config-description).\n\n This instance will represent the source database server to the Cloud SQL replica\n after the demotion operation completes.\n\n ```\n gcloud auth login\n ACCESS_TOKEN=\"$(gcloud auth print-access-token)\"\n curl --header \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"name\": \"SOURCE_REPRESENTATION_NAME\",\n \"region\": \"REGION\",\n \"databaseVersion\": \"EXTERNAL_SERVER_DATABASE_VERSION\",\n \"onPremisesConfiguration\": {\n \"hostPort\": \"EXTERNAL_SERVER_IP:EXTERNAL_SERVER_PORT\"\n }\n }' \\\n -X POST \\\n https://sqladmin.googleapis.com/sql/v1beta4/projects/PROJECT-ID/instances\n ```\n\n Use the region where you want your Cloud SQL replica to reside.\n2.\n Start the demotion process.\n\n\n Because this API call requires you to provide sensitive information, you\n should\n [use a JSON file](/sql/docs/mysql/admin-api#json-file)\n to provide your data to cURL, rather than providing it on the command line.\n\n Create the data file: \n\n ```\n {\n \"demoteMasterContext\": {\n \"replicaConfiguration\": {\n \"mysqlReplicaConfiguration\": {\n \"username\": \"REPLICATION_USERNAME\",\n \"password\": \"PASSWORD\",\n \"caCertificate\": \"EXTERNAL_SERVER_CA\",\n \"clientCertificate\": \"CLIENT_CERT\",\n \"clientKey\": \"PRIVATE_KEY\"\n }\n },\n \"masterInstanceName\": \"SOURCE_REPRESENTATION_NAME\",\n },\n }\n ```\n\n Then, call the API. \n\n ```\n curl --header \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n --header 'Content-Type: application/json' \\\n --data @PATH_TO_DATA_FILE \\\n https://sqladmin.googleapis.com/sql/v1beta4/projects/PROJECT-ID/instances/INSTANCE_NAME/demoteMaster\n ```\n\n For more information about your options for SSL/TLS, see\n [SSL/TLS options](/sql/docs/mysql/replication/external-server#ssl-options).\n For more information about the properties used by the\n `replicaConfiguration` object, see\n [Replicating from an External Server](/sql/docs/mysql/replication/replication-from-external#setup).\n3. Wait for the external replica to complete all pending transactions from\n the primary instance.\n\n When the replica is caught up, the `SHOW SLAVE STATUS` command\n will show `Seconds Behind Master` as 0, and the\n `Executed_Gtid_Set` value will be identical between the\n external replica and the Cloud SQL primary.\n4.\n Use the `mysql` client to stop replication on the external replica:\n\n ```\n STOP SLAVE\n RESET SLAVE ALL\n ```\n5.\n Wait for the Cloud SQL instance to start replicating from the\n external server, which is now the source database server.\n\n Running the `SHOW SLAVE STATUS` command on the Cloud SQL\n instance provides replication status.\n6. When the Cloud SQL instance is successfully replicating from the source database server, set the `read_only` flag on the source database server to `off` and update your applications to point to the source database server.\n\nTroubleshoot\n------------\n\n\u003cbr /\u003e\n\nWhat's next\n-----------\n\n- Learn how to [manage replicas](/sql/docs/mysql/replication/manage-replicas).\n- Learn about [requirements and best practices for the external replica configuration](/sql/docs/mysql/replication#external-read-replicas).\n- Learn more about [MySQL replication](https://dev.mysql.com/doc/refman/8.0/en/replication.html).\n- Learn more about [replication options](https://dev.mysql.com/doc/refman/8.0/en/replication-options.html).\n- Learn more about [checking replication status](https://dev.mysql.com/doc/refman/8.0/en/replication-administration-status.html).\n- Learn more about [replicating from an external server](/sql/docs/mysql/replication/replication-from-external)."]]