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

Virtual Private Cloud(VPC)ピアリングを使用すると、MongoDB Atlas データベースから Datastream にプライベート ネットワーク経由で変更データ キャプチャ(CDC)の更新をストリーミングできます。VPC ピアリングは非推移的であるため、ファイアウォール ルールを使用して Compute Engine ネットワーク アドレス変換(NAT)仮想マシン(VM)経由でトラフィックをルーティングします。また、MongoDB ユーザーを作成し、NAT VM の IP アドレスを MongoDB Atlas の許可リストに追加して、接続プロファイルを作成します。この構成では高可用性は実現されません。MongoDB ノードが接続プロファイル テストに失敗した場合は、NAT VM で起動スクリプトを手動で実行する必要があります。

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

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

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

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

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

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

NAT VM を作成する

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

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

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

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

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

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

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

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

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

  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)
    • Protocol: TCP
    • ポート: 27017
  2. 次の特性を持つ下り(外向き)ファイアウォール ルールを作成します。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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