VPC ピアリングを使用して MongoDB Atlas を構成する

このページでは、Virtual Private Cloud ピアリングを使用して Datastream と連携するように MongoDB Atlas ソースデータベースを構成する方法について説明します。説明する手順は高可用性ソリューションではないことに注意してください。MongoDB ノードが接続プロファイル テストに失敗した場合は、このページで後述する起動スクリプトをネットワーク アドレス変換(NAT)仮想マシン(VM)で手動で実行する必要があります。

Virtual Private Cloud ピアリングは推移的ではないため、Compute Engine VM を使用して NAT ゲートウェイを構成し、Datastream から MongoDB Atlas にトラフィックをルーティングする必要があります。

MongoDB データベース ユーザーを構成する

MongoDB Atlas インスタンスで Datastream を使用するには、まずデータベース ユーザーを作成し、アクセス権を付与する必要があります。

  1. MongoDB Atlas ダッシュボードで、 [Security] の下にある [Database access] をクリックします。
  2. [New database user] をクリックし、ユーザーのパスワード認証方法を選択します。
  3. Datastream ユーザーのユーザー名とパスワードを入力します。
  4. [Database user privileges] で [Grant specific user privileges] を選択します。
  5. [Specific privileges] で、次のロールを追加します:
    • readAnyDatabase
  6. [Add user] をクリックします。

Virtual Private Cloud ネットワークを設定する

プロジェクトで、Datastream と MongoDB Atlas の両方とピアリングする Virtual Private Cloud ネットワークを特定します。 Google Cloud このページでは、デフォルトの VPC とそのサブネット(us-central1 リージョンのデフォルト サブネットなど)を使用することを前提としています。

  1. 特定したネットワークの IP アドレス範囲が、Datastream ネットワークまたは MongoDB Atlas ネットワークと重複していないことを確認します。
  2. Datastream を Virtual Private Cloud ネットワークとピアリングするための プライベート接続構成を作成します。
    1. [Private connectivity method] プルダウンから [VPC peering] を選択していることを確認します。
    2. default VPC ネットワークを選択します。
    3. Datastream で使用する未使用の IP アドレス範囲(10.0.0.0/29 など)を指定します。
    4. 上り(内向き)ファイアウォール ルールに割り当てられた IP 範囲をメモします。
  3. MongoDB Atlas でネットワーク ピアリング接続を設定して、Virtual Private Cloud ネットワークを MongoDB Atlas ネットワークとピアリングします。詳細については、 MongoDB ドキュメントの ネットワーク ピアリング 接続の設定をご覧ください。
    1. MongoDB Atlas でプロジェクト ID とデフォルトの VPC 名を指定します。 Google Cloud
    2. MongoDB Atlas から提供されたプロジェクト ID と VPC 名をメモして、 サイドでピアリングを完了します。 Google Cloud
  4. 接続を作成したら、MongoDB Atlas プロジェクトで [Network Access] > [VPC Peering] タブに移動し、下り(外向き)ファイアウォール ルールのクラスレス ドメイン間ルーティング(CIDR)ブロックをメモします。

NAT VM を作成する

  1. コンソールで、[VM インスタンス] ページに移動します。 Google Cloud

    [VM インスタンス] に移動

  2. [インスタンスを作成] をクリックします。

  3. [名前] フィールドに、VM の名前(mongo-nat-gateway など)を入力します。

  4. [リージョン] フィールドで、デフォルトの VPC 内のリージョン(us-central1 など)を選択します。

  5. ナビゲーション メニューで、[ネットワーキング] をクリックします。

  6. [ネットワーク タグ] フィールドに、mongo-nat-vm などのタグを追加します。このタグは、ファイアウォール ルールで使用されます。

  7. [IP 転送] で、[有効にする] チェックボックスをオンにします。

  8. [**ネットワーク インターフェース**] で、デフォルトの VPC とそのサブネット(us-central1default など)を選択します。

  9. ナビゲーション メニューで、[詳細設定] をクリックします。

  10. [自動化] セクションの [起動スクリプト] フィールドに、次のスクリプトを貼り付けます。PRIVATE_SRV_RECORD は、MongoDB Atlas クラスタのプライベート SRV レコード(my-cluster-pri.abcde.mongodb.net など)に置き換えます。

    #!/bin/bash
    
    # --- Startup script for MongoDB Atlas NAT gateway ---
    # This script has two main functions:
    # 1. Resolves the IP address of a MongoDB Atlas node from its SRV record.
    # 2. Configures iptables to forward traffic to the resolved MongoDB IP.
    # --------------------------------------------------------------------------
    
    # --- Part 1: Resolve MongoDB node IP address ---
    
    #
    # EDIT THIS LINE to match your Mongo Atlas private SRV record
    #
    export SRV_RECORD=PRIVATE_SRV_RECORD
    
    echo "Resolving SRV record for: $SRV_RECORD"
    
    # Function to install DNS utilities if needed
    install_dns_tools() {
        echo "'dig' not found. Attempting to install DNS utilities..."
        if command -v apt-get &> /dev/null; then
            # Wait for any existing apt processes to finish before trying to install packages.
            # This is common on VM startup where the system might be running automatic updates.
            echo "Checking for and waiting on existing apt-get processes..."
            while fuser /var/lib/apt/lists/lock /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do
                echo "Another apt process is running. Waiting 10 seconds..."
                sleep 10
            done
            echo "Apt lock is free. Proceeding with installation."
    
            apt-get update && apt-get install -y dnsutils
        else
            echo "Error: Could not find apt-get to install DNS utilities."
            exit 1
        fi
    
        # Verify that dig is now available
        if ! command -v dig &> /dev/null; then
            echo "Error: Failed to install DNS utilities."
            exit 1
        fi
    }
    
    # Check if 'dig' is installed. If not, install it.
    if ! command -v dig &> /dev/null; then
        install_dns_tools
    fi
    
    echo "Using 'dig' for DNS resolution."
    # The `+short` option provides a concise output.
    # We use `awk` to grab the 4th column (the hostname) and `head` to get the first one.
    NODE_HOSTNAME=$(dig +short SRV "_mongodb._tcp.${SRV_RECORD}" | awk '{print $4}' | head -n 1)
    if [ -n "$NODE_HOSTNAME" ]; then
        NODE_IP=$(dig +short A "$NODE_HOSTNAME")
    fi
    
    # Check if the SRV lookup was successful and we got a hostname.
    if [ -z "$NODE_HOSTNAME" ]; then
        echo "Error: Could not resolve SRV record. Check the hostname and your
        network connection."
        exit 1
    fi
    
    echo "Found node hostname: $NODE_HOSTNAME"
    
    # Check if the A record lookup was successful.
    if [ -z "$NODE_IP" ]; then
        echo "Error: Could not resolve the IP address for node: $NODE_HOSTNAME"
        exit 1
    fi
    
    # 3. Print the final result of the lookup.
    echo "Successfully resolved IP address of a node: $NODE_IP"
    
    # --- Part 2: Configure iptables for NAT ---
    
    # Substitute the resolved IP address into the DB_ADDR variable.
    export DB_ADDR=$NODE_IP
    export DB_PORT=27017
    
    # Enable the VM to receive packets whose destinations do
    # not match any running process local to the VM
    echo 1 > /proc/sys/net/ipv4/ip_forward
    
    # Ask the Metadata server for the IP address of the VM nic0
    # network interface:
    md_url_prefix="http://169.254.169.254/computeMetadata/v1/instance"
    vm_nic_ip="$(curl -H "Metadata-Flavor: Google" ${md_url_prefix}/network-interfaces/0/ip)"
    
    # Clear any existing iptables NAT table entries (all chains):
    iptables -t nat -F
    
    # Create a NAT table entry in the prerouting chain, matching
    # any packets with destination database port, changing the destination
    # IP address of the packet to the MongoDB instance IP address:
    iptables -t nat -A PREROUTING \
         -p tcp --dport $DB_PORT \
         -j DNAT \
         --to-destination $DB_ADDR
    
    # Create a NAT table entry in the postrouting chain, matching
    # any packets with destination database port, changing the source IP
    # address of the packet to the NAT VM's primary internal IPv4 address:
    iptables -t nat -A POSTROUTING \
         -p tcp --dport $DB_PORT \
         -j SNAT \
         --to-source $vm_nic_ip
    
    # Save iptables configuration:
    iptables-save
    
    echo "Startup script completed successfully. iptables rules are configured and saved."
  11. [作成] をクリックして VM を起動します。

  12. VM が実行されたら、その内部 IP アドレス(10.128.0.2 など)をメモします。

上り(内向き)と下り(外向き)のファイアウォール ルールを作成する

VPC ネットワークに 2 つのファイアウォール ルールを作成する必要があります。

  1. 次の特性を持つ上り(内向き)ファイアウォール ルールを作成します。

    • 名前: INGRESS_RULE_NAME
    • 方向: 上り(内向き)
    • アクション: 許可
    • ターゲット パラメータ: mongo-nat-vm ターゲットタグ
    • ソース パラメータ: Datastream プライベート接続構成で使用される IP アドレス範囲(10.0.0.0/29 など)
    • プロトコル: TCP
    • ポート: 27017
  2. 次の特性を持つ下り(外向き)ファイアウォール ルールを作成します。

    • 名前: EGRESS_RULE_NAME
    • 方向: 下り(外向き)
    • アクション: 許可
    • ターゲット パラメータ: mongo-nat-vm ターゲットタグ
    • 宛先パラメータ: MongoDB Atlas CIDR ブロック(192.168.240.0/21 など)
    • プロトコル: TCP
    • ポート: 27017

MongoDB Atlas で IP 許可リストを構成する

MongoDB Atlas のセキュリティ設定で NAT VM の内部 IP アドレスを許可します。

  1. MongoDB Atlas アカウントにログインします。
  2. ナビゲーション メニューで [セキュリティ] をクリックし、[ネットワーク アクセス] をクリックします。
  3. [IP アドレスを追加] をクリックします。
  4. [アクセスリスト エントリ] フィールドに、VPC ネットワークで作成した NAT VM インスタンスの内部 IP アドレスを入力します。
  5. [確認] をクリックして、ステータスが [Active] に変わるまで待ちます。

接続プロファイルを作成する

データベース用の Datastream 接続プロファイルを作成します。

  1. コンソールで [**接続プロファイル**] ページに移動します。 Google Cloud

    [接続プロファイル] ページに移動

  2. [プロファイルの作成] をクリックして [MongoDB] を選択します。

  3. [Hostname] フィールドに、VPC ネットワークで作成した NAT VM インスタンスの内部 IP アドレスを入力します。

  4. [Port] フィールドに、「27017」と入力します。

  5. データベース ユーザーのユーザー名とパスワードを入力します。

  6. tls ラベルと tls_allow_invalid_hostnames ラベルを追加し、値を true に設定します。ラベルの設定の詳細については、MongoDB データベースの接続プロファイルを作成するをご覧ください。

  7. 接続方法として [プライベート接続] を選択します。

  8. 作成したプライベート接続構成を選択します。

  9. [作成] をクリックして接続プロファイルを保存します。

  10. テストを実行して、データベースへの接続を確認します。