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. 사용자 추가 를 클릭합니다.

Virtual Private Cloud 네트워크 설정

Datastream 및 MongoDB Atlas와 모두 피어링할 Google Cloud 프로젝트의 Virtual Private Cloud 네트워크를 식별합니다. 이 페이지에서는 기본 VPC 및 서브넷(예: us-central1 리전의 기본 서브넷)을 사용한다고 가정합니다.

  1. 식별한 네트워크에 Datastream 또는 MongoDB Atlas 네트워크와 겹치는 IP 주소 범위가 없는지 확인합니다.
  2. 비공개 연결 구성 을 만들어 Datastream을 Virtual Private Cloud 네트워크와 피어링합니다.
    1. Private connectivity method(비공개 연결 방법) 드롭다운에서 VPC 피어링 을 선택해야 합니다.
    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(VPC 피어링) 탭으로 이동하여 이그레스 방화벽 규칙의 클래스 없는 도메인 간 라우팅(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 네트워크에서 두 개의 방화벽 규칙을 만들어야 합니다.

  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. 확인 을 클릭하고 상태가 활성 으로 변경될 때까지 기다립니다.

연결 프로필 만들기

데이터베이스의 Datastream 연결 프로필을 만듭니다.

  1. 콘솔에서 연결 프로필 페이지로 이동합니다. Google Cloud

    연결 프로필 페이지로 이동

  2. 프로필 만들기 를 클릭하고 MongoDB 를 선택합니다.

  3. 호스트 이름 필드에 VPC 네트워크에서 만든 NAT VM 인스턴스의 내부 IP 주소를 입력합니다.

  4. 포트 필드에 27017을 입력합니다.

  5. 데이터베이스 사용자의 사용자 이름과 비밀번호를 입력합니다.

  6. tlstls_allow_invalid_hostnames 라벨을 추가하고 값을 true로 설정합니다. 라벨 설정에 대한 자세한 내용은 MongoDB 데이터베이스의 연결 프로필 만들기를 참조하세요.

  7. 연결 방법으로 비공개 연결 을 선택합니다.

  8. 만든 비공개 연결 구성을 선택합니다.

  9. 만들기 를 클릭하여 연결 프로필을 저장합니다.

  10. 테스트를 실행하여 데이터베이스 연결을 확인합니다.