Se a sua base de dados de origem estiver dentro de uma VPN (por exemplo, na AWS ou na sua VPN no local), também tem de usar uma VPN no lado de destino para estabelecer ligação à origem.
Existem muitos produtos de VPN que pode usar. Os passos para configurar VPNs variam de um produto para outro, mas são fundamentalmente semelhantes. Esta secção contém exemplos que usam VPNs da AWS e da Google Cloud .
A firewall do servidor da base de dados de origem tem de ser configurada para permitir todo o intervalo de IP interno atribuído para a ligação de serviço privado da rede VPC que a instância de destino do Cloud SQL vai usar como o campo privateNetwork das respetivas definições de ipConfiguration.
Para encontrar o intervalo de IPs internos na consola:
No lado Google Cloud , crie uma VPN na nuvem com encaminhamento estático.
Em conjunto, a sequência geral de passos tem o seguinte aspeto:
Na Google Cloud consola > Redes VPC > Endereços IP externos, reserve um endereço IP estático para usar na Cloud VPN.
Na consola da VPC da AWS:
Crie um gateway do cliente.
Crie um novo gateway privado virtual ou adicione um existente à VPC associada à sua base de dados.
Em Tabelas de rotas, adicione a propagação de rotas:
Clique em Editar, selecione a caixa de verificação propagate e clique em Guardar para
adicionar o intervalo de endereços IP da sua rede Google Cloud VPC como o intervalo de destino.
Na consola da VPC da AWS, crie a VPN:
Em Ligações VPN, selecione Ligações VPN site a site.
Selecione Criar ligação VPN.
Introduza um nome para a ligação VPN.
Para Virtual Private Gateway, selecione o gateway privado que criou ou selecionou anteriormente neste procedimento.
Para o Customer Gateway, selecione o gateway do cliente que criou
anteriormente neste procedimento.
Para Opções de encaminhamento, selecione Estático e especifique o endereço IP estático que reservou para a VPN na nuvem como um CIDR (adicione /32).
Transfira a configuração para guardar as definições.
Guarde o ficheiro como Predefinição.
Encontre as secções Túneis IP Sec n.º 1 e n.º 2.
Tenha em atenção a versão do IKE e a chave pré-partilhada para cada túnel.
Tome nota do endereço IP do Virtual Private Gateway para cada túnel.
Tome nota do endereço IP da opção de configuração de rota estática para cada túnel.
Na Google Cloud consola > Conetividade híbrida > VPN:
Clique em Criar ligação VPN.
Selecione a sua rede de VPC e região.
Para a VPN do Google Cloud, use o endereço IP estático que reservou anteriormente
neste procedimento.
Use um Pre-shared key e um tipo de chave da configuração da AWS que transferiu anteriormente neste procedimento.
Selecione a opção de encaminhamento Com base no trajeto e adicione dois túneis. Para o campo Intervalo de IPs da rede remota de cada túnel, use um endereço IP da opção de configuração de trajeto estático das secções IP Sec Tunnel do ficheiro de configuração da AWS que transferiu anteriormente neste procedimento.
Clique em Criar.Intervalo de IPs da rede remota
Na consola do AWS RDS:
Selecione um grupo de segurança.
Adicione regras de firewall de entrada para permitir todos os protocolos e portas da
VPN do Google Cloud.
Os túneis VPN devem começar a comunicar em breve. No lado da AWS, no painel de controlo da VPC, os estados dos túneis são UP. No lado do GCP, veja o tráfego entre as VPNs na consola do Cloud Logging no projeto Cloud VPN gateway.
Exemplo 2: AWS com VPN de alta disponibilidade do Google Cloud com rotas dinâmicas
Para obter o intercâmbio da rede da VPC com uma VPN de alta disponibilidade (rotas dinâmicas) para a AWS, tem de exportar
rotas BGP para a VPC com intercâmbio do Cloud SQL e criar uma rota anunciada personalizada
no Cloud Router para a rota importada da VPC com intercâmbio do Cloud SQL. Nesse momento, o Cloud Router está a anunciar rotas da AWS para a VPC do Cloud SQL e vice-versa. As regras de firewall em ambos os lados também têm de corresponder ao CIDR da rota de peering do Cloud SQL.
No lado da AWS, pode seguir os três primeiros passos no Exemplo 1,
exceto selecionar Dinâmico em vez de Estático em Opções de encaminhamento.
Selecione a configuração de interligação VPC do Cloud SQL na consola
e tome nota dos intervalos de IP de destino em ROTAS IMPORTADAS.
Para mais informações, consulte o artigo Importar e exportar rotas personalizadas.
Edite este intercâmbio de VPCs e selecione Import Custom Routes e
Export Custom Routes nos detalhes da ligação de intercâmbio de VPCs,
e clique em GUARDAR.
O peering recebe agora rotas dinâmicas da sua VPC, como as rotas provenientes de pares BGP. Isto permite o tráfego da VPN para a rede com peering.
No entanto, o Cloud Router ainda não está a anunciar esta rota a outras redes.
Para tal, tem de adicionar rotas anunciadas personalizadas no Cloud Router para que a sua VPC anuncie as rotas importadas a outras redes. Para mais
informações, consulte o artigo Importar e exportar rotas personalizadas.
Adicione o seu intervalo de IP personalizado DESTINATION_IP_RANGE como um trajeto personalizado nos trajetos anunciados da configuração do Cloud Router. As redes com peering de BGP estão agora a receber anúncios das rotas de rede do Cloud SQL importadas, DESTINATION_IP_RANGE. O tráfego nessas redes ligadas à VPN destinadas à VPC em peering do Cloud SQL é agora encaminhado através do túnel VPN.
Permitir que os trajetos sejam propagados nas tabelas de trajetos da AWS. Certifique-se de que as tabelas de rotas da AWS
para as sub-redes que contêm a sua base de dados de origem contêm uma entrada para o intervalo DESTINATION_IP_RANGE que encaminha para o gateway privado virtual da VPN.
Adicione uma regra de entrada de firewall do grupo de segurança para permitir o tráfego para
DESTINATION_IP_RANGETCP port 3306.
Já é possível estabelecer a conetividade.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-21 UTC."],[[["\u003cp\u003eConnecting a source database within a VPN to a destination requires a VPN on the destination side, regardless of the VPN product used.\u003c/p\u003e\n"],["\u003cp\u003eThe source database's firewall must allow the entire internal IP range allocated for the private service connection of the VPC network used by the Cloud SQL destination instance.\u003c/p\u003e\n"],["\u003cp\u003eWhen using AWS with Google Cloud Classic VPN, static routing is employed, necessitating the reservation of a static IP address in Google Cloud and the creation of a customer gateway and VPN in AWS.\u003c/p\u003e\n"],["\u003cp\u003eFor AWS with Google Cloud HA VPN using dynamic routes, BGP routes must be exported to the Cloud SQL peered VPC, and a custom advertised route in Cloud Router must be created to facilitate route advertisement between AWS and Cloud SQL.\u003c/p\u003e\n"],["\u003cp\u003eTo establish connectivity in the HA VPN setup, firewall rules on both sides need to match the Cloud SQL peering route CIDR, and AWS route tables must have an entry for the destination IP range that directs traffic through the VPN Virtual Private Gateway.\u003c/p\u003e\n"]]],[],null,["# Configure connectivity using VPNs\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nMySQL \\| [PostgreSQL](/database-migration/docs/postgres/configure-connectivity-vpns \"View this page for the PostgreSQL version of Database Migration Service.\") \\| [PostgreSQL to AlloyDB](/database-migration/docs/postgresql-to-alloydb/configure-connectivity-vpns \"View this page for the PostgreSQL to AlloyDB version of Database Migration Service.\")\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nOverview\n--------\n\nIf your source database is inside a VPN (in AWS, for example, or your\non-premises VPN), you also need to use a VPN on the destination side to connect\nto the source.\n\nThere are many VPN products you can use. The steps to configure VPNs vary from\none product to another, but all of them are fundamentally similar. This section\ncontains examples using AWS and Google Cloud VPNs.\n\nThe source database server's firewall must be configured to allow the entire **internal\nIP range** allocated for the **private service connection** of the\nVPC network that the Cloud SQL destination instance is going to use as the\n**privateNetwork** field of its [**ipConfiguration** settings](/sql/docs/mysql/replication/replication-from-external#setup-replica-instance).\n\nTo find the **internal IP range** in the console:\n\n1. [Go to the VPC networks page](https://console.cloud.google.com/networking/networks/list) in the Google Cloud console.\n\n2. Select the VPC network that you want to use.\n\n3. Select **Private services access** \\\u003e **Allocated IP ranges for services**.\n\n4. Find the **Internal IP range** associated with the connection created by **servicenetworking-googleapis-com**.\n\n| Note: To use Virtual Private Cloud networking, you must enable the [Service Networking API](https://console.cloud.google.com/apis/library/servicenetworking.googleapis.com) for your Google Cloud project.\n\nExample 1: AWS with Google Cloud Classic VPN with static routes\n---------------------------------------------------------------\n\nFind more complete, step-by-step documentation in the following links:\n\n- On the AWS side, set up a [Site to Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/SetUpVPNConnections.html).\n- On the Google Cloud side, create a [Cloud VPN](/vpn/docs/how-to/creating-static-vpns) using static routing.\n\n\u003cbr /\u003e\n\nPut together, the overall sequence of steps looks like the following:\n\n1. In Google Cloud console \\\u003e VPC Networks \\\u003e External IP addresses, reserve a static IP address to use for the Cloud VPN.\n2. In the AWS VPC console:\n 1. Create a customer gateway.\n 2. Create a new virtual private gateway or add an existing one to the VPC associated with your database.\n 3. In **Routes Tables** add **route propagation**:\n 4. Click **Edit** , check the **propagate** checkbox and **Save** to add the IP address range of your Google Cloud VPC network as the destination range.\n3. In the AWS VPC console, create the VPN:\n 1. Under **VPN Connections** , select **Site-to-site VPN Connections**.\n 2. Select **Create VPN Connection**.\n 3. Enter a name for the VPN connection.\n 4. For **Virtual Private Gateway**, select the private gateway that you created or selected earlier in this procedure.\n 5. For **Customer Gateway**, select the customer gateway that you created earlier in this procedure.\n 6. For **Routing Options** , select **Static**, and specify the static IP address you reserved for the Cloud VPN as a CIDR (add /32).\n 7. Download the configuration to save the settings.\n 1. Save the file as **Default**.\n 2. Find the sections **IP Sec Tunnels** #1 and #2.\n 3. Note the IKE version and **Pre-Shared Key** for each tunnel.\n 4. Note the IP address for the **Virtual Private Gateway** for each tunnel.\n 5. Note the IP address for the **Static Route Configuration option** for each tunnel.\n4. In Google Cloud, create a [Classic VPN using static routing](/vpn/docs/how-to/creating-static-vpns).\n 1. In Google Cloud console \\\u003e Hybrid Connectivity \\\u003e VPN:\n 2. Click **Create VPN connection** .\n 1. Select your VPC network and region.\n 2. For the Cloud VPN, use the static IP address you reserved earlier in this procedure.\n 3. Use a `Pre-shared key` and key type from the AWS configuration you downloaded earlier in this procedure.\n 4. Select the **Route based** routing option and add two tunnels; for each tunnel's **Remote network IP range** field, use an IP address for the **Static Route Configuration option** from the `IP Sec Tunnel` sections of the AWS configuration file you downloaded earlier in this procedure.\n 5. Click **Create** .**Remote network IP range**\n\n\u003c!-- --\u003e\n\n5. In the AWS RDS console:\n 1. Select a security group.\n 2. Add inbound firewall rules to allow all protocols and ports from the Cloud VPN.\n\nThe VPN tunnels should begin communicating shortly. On the AWS side, in the\nVPC Dashboard, the tunnel statuses are `UP`. On the GCP\nside, view the traffic between the VPNs in the\n[Cloud Logging](https://console.cloud.google.com/logs) console in the\n`Cloud VPN gateway` project.\n\nExample 2: AWS with Google Cloud HA VPN with dynamic routes\n-----------------------------------------------------------\n\nTo get VPC Peering with an HA VPN (dynamic routes) to AWS, you need to export BGP routes to the Cloud SQL peered VPC, and create a custom advertised route in Cloud Router for the Cloud SQL peered VPC imported route. At that point, Cloud Router is advertising AWS routes to the Cloud SQL VPC and the other way around. The firewall rules on both sides also need to match the Cloud SQL peering route CIDR.\n\nOn the AWS side, you can follow the first three steps in [Example 1](#static-routes),\nexcept select **Dynamic** instead of **Static** under **Routing options**.\n\n1. Select your Cloud SQL VPC Peering configuration in the [Console](https://console.cloud.google.com/networking/peering) and note the **Destination IP ranges** under **IMPORTED ROUTES** . For more information, see [Importing and exporting custom routes](/vpc/docs/vpc-peering#importing-exporting-routes).\n2. Edit this VPC peering and check `Import Custom Routes` and `Export Custom Routes` in the VPC Peering connection details, and click **SAVE** .\n\n The peering now receives dynamic routes from your VPC like the routes\n coming from BGP peers. This allows traffic from the VPN to the peered network.\n However, Cloud Router is not yet advertising this route to other networks.\n To do so, you need to add custom advertised routes in the Cloud Router so\n that your VPC advertises the imported routes to other networks. For more\n information, see [Importing and exporting custom routes](/network-connectivity/docs/router/concepts/advertised-routes#overview-am).\n3. Add your \u003cvar translate=\"no\"\u003eDESTINATION_IP_RANGE\u003c/var\u003e custom IP range as a custom route in the Cloud Router configuration advertised routes. BGP peered networks are now receiving advertisements of the **imported Cloud SQL\n network routes** , \u003cvar translate=\"no\"\u003eDESTINATION_IP_RANGE\u003c/var\u003e. Traffic on those VPN-connected networks bound for the Cloud SQL peered VPC are now routed through the VPN tunnel.\n4. Allow routes to propagate in AWS route tables. Make sure AWS route tables for the subnets that contain your source database contain an entry for the \u003cvar translate=\"no\"\u003eDESTINATION_IP_RANGE\u003c/var\u003e range that routes to the VPN Virtual Private Gateway.\n5. Add a security group firewall inbound rule to allow traffic for \u003cvar translate=\"no\"\u003eDESTINATION_IP_RANGE\u003c/var\u003e `TCP port 3306`. Connectivity can now be established."]]