이 문서는 설계자와 운영 및 관리 팀에서 일하는 사람들을 대상으로 합니다. 이 문서에서는 Google Cloud에서 자체 배포에 사용할 수 있는 예시 패턴을 설명합니다. 이 패턴에서 Cloud DNS는 콘텐츠를 제공하는 관리형 인스턴스 그룹의 Compute Engine 인스턴스로 트래픽을 보냅니다. 서비스 중단 시 Cloud DNS 영역을 업데이트하고 Cloud Storage의 정적 사이트로 장애 조치합니다. 이 자습서를 완료하려면 이 문서에서 제어하고 사용하려는 등록된 도메인 이름이 필요합니다. 프로덕션 배포에서 웹 사이트에는 이 문서에 표시된 것보다 관리형 인스턴스 그룹 VM(가상 머신)에 더 많은 파일과 추가 애플리케이션 코드가 포함될 수 있습니다. 그런 다음 Cloud Storage는 최소한의 기능을 제공하는 보다 제한된 정적 버전을 호스팅합니다. 웜 장애 조치 시나리오에서 사용자는 관리형 인스턴스 그룹이 복구되어 전체 웹 사이트 경험을 위해 트래픽을 처리할 수 있을 때까지 이 제한된 웹 사이트를 볼 수 있습니다. 이 자습서에서는 리소스를 배포하여 다음 이미지와 같이 환경을 생성합니다. 장애 조치가 필요한 경우 다음 이미지와 같이 트래픽을 Cloud Storage로 전달하도록 Cloud DNS 구성을 업데이트합니다. 이 웜 장애 조치 패턴은 기본 지역이 실패할 때만 사용하는 다른 지역에서 다른 관리형 인스턴스 그룹을 실행하는 비용의 균형을 맞춥니다. Cloud Storage를 사용하는 정적 사이트 비용은 다른 관리형 인스턴스 그룹을 실행하는 것보다 저렴하지만 호스팅 옵션 간에 Cloud DNS를 업데이트할 때 약간의 지연이 있습니다. Cloud Storage의 제한된 웹사이트 경험은 완전히 사용할 수 없는 웹사이트와 열악한 고객 경험보다 낫습니다. 장애 조치를 제어하기 위해 Cloud DNS 대신 외부 HTTP(S) 부하 분산을 사용하는 대체 접근 방식은 Compute Engine 및 Cloud Storage로 복구 가능한 웜 웹 서버 배포를 참조하세요. 이 패턴은 Cloud DNS가 없거나 사용하고 싶지 않은 경우에 유용합니다. Google Cloud에서 안정적인 애플리케이션을 실행하려면 중단을 처리하도록 애플리케이션 인프라를 설계하는 것이 좋습니다. 애플리케이션 및 비즈니스 요구 사항에 따라 콜드 장애 조치, 웜 장애 조치 또는 핫 장애 조치 패턴이 필요할 수 있습니다. 자신의 애플리케이션에 가장 적합한 접근 방식을 결정하는 방법에 대한 자세한 내용은 재해 복구 계획 가이드를 참조하세요. 이 문서는 기본 Apache 웹 서버를 사용하지만 인프라 배포에 대한 동일한 접근 방식이 생성해야 하는 다른 애플리케이션 환경에 적용됩니다. ## 목표 - 커스텀 VM 이미지로 지역 관리형 인스턴스 그룹 만들기 - Cloud Storage 버킷 생성 - Cloud DNS 영역 생성 및 구성 - 업데이트된 Cloud DNS 레코드로 웜 웹 서버 장애 조치 테스트 - 업데이트된 Cloud DNS 레코드로 복구 및 장애 복구 테스트 ## 비용 이 가이드에서는 청구 가능한 다음 Google Cloud 구성요소를 사용합니다. 예상 사용량을 기반으로 비용 견적을 생성하려면 가격 계산기 사용 ## 시작하기 전에 조직에서 GCP 환경에 제약조건을 적용하는 경우 이 문서의 일부 단계가 제대로 작동하지 않을 수 있습니다. 이 경우 공개 IP 주소 또는 서비스 계정 키 생성과 같은 작업을 완료하지 못할 수 있습니다. 제약조건에 대한 오류를 반환하는 요청을 하는 경우 제한된 Google Cloud 환경에서 애플리케이션 개발 방법을 참조하세요. - Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Google 제품의 성능을 평가하세요. 신규 고객은 또한 워크로드를 실행, 테스트 및 배포할 수 있는 $300의 무료 크레딧을 받습니다. - Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다. - 클라우드 프로젝트에 결제가 사용 설정되어 있는지 확인하세요. 프로젝트에서 결제가 사용 설정되었는지 확인하는 방법 알아보기 - Compute Engine API 사용 설정 - Google Cloud CLI 설치 및 초기화 - Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다. - 클라우드 프로젝트에 결제가 사용 설정되어 있는지 확인하세요. 프로젝트에서 결제가 사용 설정되었는지 확인하는 방법 알아보기 - Compute Engine API 사용 설정 - Google Cloud CLI 설치 및 초기화 Google Cloud CLI를 설치하지 않고 Google Cloud Console에서 Google Cloud CLI를 실행할 수 있습니다. Google Cloud Console에서 gcloud CLI를 실행하려면 Cloud Shell을 사용하세요. ## 환경 준비 이 섹션에서는 리소스 이름 및 위치에 대한 몇 가지 변수를 정의합니다. 이러한 변수는 리소스를 배포할 때 Google Cloud CLI 명령어에서 사용됩니다. 달리 명시되지 않는 한 이 가이드 전체에서 Cloud Shell 또는 로컬 개발 환경에 모든 명령을 입력합니다. 바꾸다 자신의 프로젝트 ID로. 원하는 경우 다음과 같이 리소스를 검색하고 식별하는 데 도움이 되도록 리소스에 고유한 이름 접미사를 제공합니다. 프로젝트_ID 앱 다음과 같이 두 지역을 지정합니다. 그리고 미국 서부1 및 해당 지역 중 하나 내의 영역(예: 미국-서부2 . 이 영역은 관리형 인스턴스 그룹의 이미지를 만드는 데 사용되는 초기 기본 VM이 생성되는 위치를 정의합니다. 미국 서부1-a 마지막으로 다음과 같이 정적 웹사이트에 사용되는 도메인을 설정합니다. example.com 프로젝트_ID= PROJECT_IDNAME_SUFFIX= appREGION1= us-west1REGION2= us-west2ZONE= us-west1-aDOMAIN= example.com ## VPC 및 서브넷 생성 VM에 대한 네트워크 액세스를 제공하려면 Virtual Private Cloud(VPC) 및 서브넷을 생성합니다. 두 지역에 관리형 인스턴스 그룹이 필요하므로 각 지역에 하나의 서브넷을 만듭니다. 환경에서 사용 중인 IP 주소 범위를 관리하기 위한 커스텀 서브넷 모드의 이점에 대한 자세한 내용은 커스텀 모드 VPC 네트워크 사용을 참조하세요. 사용자 지정 서브넷 모드로 VPC를 생성합니다. gcloud compute networks create network-$NAME_SUFFIX --subnet-mode=custom 이제 각 지역에 하나씩 새 VPC에 두 개의 서브넷을 만듭니다. 다음과 같은 고유한 주소 범위를 정의합니다. 그리고 10.1.0.0/20 , 네트워크 범위에 맞는: 10.2.0.0/20 gcloud compute networks subnets create \ subnet-$NAME_SUFFIX-$REGION1 \ --network=network-$NAME_SUFFIX \ --range= 10.1.0.0/20\ --region=$REGION1 gcloud compute networks subnets create \ subnet-$NAME_SUFFIX-$REGION2 \ --network=network-$NAME_SUFFIX \ --range= 10.2.0.0/20\ --region=$ 지역2 ## 방화벽 규칙 만들기 네트워크 트래픽이 VPC에서 올바르게 흐르도록 하려면 방화벽 규칙을 사용하십시오. 부하 분산기 및 관리형 인스턴스 그룹에 대한 웹 트래픽 및 상태 확인을 허용하는 방화벽 규칙을 만듭니다. gcloud compute firewall-rules create allow-http-$NAME_SUFFIX \ --network=network-$NAME_SUFFIX \ --direction=INGRESS \ --priority=1000 \ --action=ALLOW \ --rules=tcp:80 \ -- source-ranges=0.0.0.0/0 \ --target-tags=http-server gcloud compute firewall-rules create allow-health-check-$NAME_SUFFIX \ --network=network-$NAME_SUFFIX \ --action=allow \ - -direction=ingress \ --source-ranges=130.211.0.0/22,35.191.0.0/16 \ --target-tags=allow-health-check \ --rules=tcp:80 HTTP 규칙은 다음과 같은 모든 VM에 대한 트래픽을 허용합니다. http-servertag가 적용되고 모든 소스에서 0.0.0.0/0 범위. 상태 확인 규칙의 경우 Google Cloud의 기본 범위는 플랫폼이 리소스 상태를 올바르게 확인할 수 있도록 설정됩니다. 기본 VM 이미지의 초기 구성에 SSH 트래픽을 허용하려면 다음을 사용하여 방화벽 규칙 범위를 환경으로 지정합니다. --소스-범위 매개변수. 조직에서 사용하는 소스 범위를 결정하려면 네트워크 팀과 협력해야 할 수 있습니다. 바꾸다 고유한 IP 주소 범위 사용: IP_ADDRESS_SCOPE gcloud compute firewall-rules create allow-ssh-$NAME_SUFFIX \ --network=network-$NAME_SUFFIX \ --direction=INGRESS \ --priority=1000 \ --action=ALLOW \ --rules=tcp:22 \ -- 소스 범위= IP_ADDRESS_SCOPE 방화벽 규칙을 만든 후 세 가지 규칙이 추가되었는지 확인합니다. gcloud compute firewall-rules list \ --project=$PROJECT_ID \ --filter="NETWORK=network-$NAME_SUFFIX"다음 예제 출력은 세 가지 규칙이 올바르게 생성되었음을 보여줍니다. 이름 네트워크 방향 우선 순위 허용 allow-health-check-app network-app INGRESS 1000 tcp:80 allow-http-app network-app INGRESS 1000 tcp:80 allow-ssh-app network-app INGRESS 1000 tcp:22 ## 기본 VM 이미지 생성 및 구성 추가 구성 없이 배포하는 동일한 VM을 만들려면 사용자 지정 VM 이미지를 사용합니다. 이 이미지는 OS 및 Apache 구성을 캡처하고 다음 단계에서 관리형 인스턴스 그룹에 각 VM을 만드는 데 사용됩니다. VM에서 기본 영구 디스크의 index.html 파일 및 마운트 /var/www/example.com. 다음 위치에 있는 Apache 구성 파일 /etc/apache2/sites-available/example.com.conf는 마운트된 영구 디스크 위치 다음 다이어그램은 영구 디스크에 저장된 Apache에서 제공하는 기본 HTML 페이지를 보여줍니다. 다음 단계에서 이 환경을 빌드합니다. 영구 디스크가 연결된 기본 VM을 만듭니다. gcloud 컴퓨팅 인스턴스 생성 vm-base-$NAME_SUFFIX \ --zone=$ZONE \ --machine-type=n1-standard-1 \ --subnet=subnet-$NAME_SUFFIX-$REGION1 \ --tags=http-server \ --image=debian-10-buster-v20210420 \ --image-project=debian-cloud \ --boot-disk-size=10GB \ --boot-disk-type=pd-balanced \ --boot-disk- device-name=vm-base-$NAME_SUFFIX \ --create-disk=type=pd-ssd,name=disk-base-$NAME_SUFFIX,크기=10GB,device-name=disk-base-$NAME_SUFFIX 이 문서의 시작 부분에 정의된 매개변수를 사용하여 VM의 이름을 지정하고 올바른 서브넷에 연결합니다. 부팅 디스크 및 데이터 디스크의 매개변수에서도 이름이 지정됩니다. 간단한 웹 사이트를 설치하고 구성하려면 먼저 SSH를 사용하여 기본 VM에 연결합니다. gcloud compute ssh vm-base-$NAME_SUFFIX --zone=$ZONE VM에 대한 SSH 세션에서 선택한 편집기에서 VM을 구성하는 스크립트를 만듭니다. 다음 예에서는 Nano를 편집기로 사용합니다. 나노 구성 VM. 다음 구성 스크립트를 파일에 붙여넣습니다. 빈/배시 NAME_SUFFIX= app# 기본 웹사이트 파일용 디렉토리 생성 sudo mkdir -p /var/www/example.com sudo chmod a+w /var/www/example.com sudo chown -R www-data: /var/www/example.com # 디스크 이름을 찾은 다음 포맷하고 마운트합니다. DISK_NAME="google-disk-base-$NAME_SUFFIX"DISK_PATHfind /dev/disk/by-id -name DISK_NAME}"| xargs -Ireadlink -fsudo mkfs.ext4 -m 0 - E lazy_itable_init=0,lazy_journal_init=0,discard $DISK_PATH sudo mount -o discard,defaults $DISK_PATH /var/www/example.com # 아파치 설치 sudo apt-get update&& sudo apt-get -y install apache2 # 마운트된 영구 디스크에 기본 HTML 파일을 씁니다. sudo tee -a /var/ www/example.com/index.html >/dev/null EOF' HA / DR 예시

Cloud Storage로의 웜 장애 조치가 있는 Compute Engine 웹사이트에 오신 것을 환영합니다p>

*:80> ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined EOF # Apache 구성 파일을 활성화하고 서비스를 다시 로드합니다. sudo a2dissite 000-default sudo a2ensite example.com.conf sudo systemctl reload apache2 업데이트 다음과 같이 이 문서의 시작 부분에 설정된 값과 일치하는 변수 NAME_SUFFIX 앱 파일을 작성하고 편집기를 종료하십시오. 예를 들어 Nano에서는 다음을 사용합니다. Ctrl-O를 눌러 파일을 작성한 다음 종료합니다. Ctrl-X 구성 스크립트를 실행 가능하게 만든 다음 실행합니다. chmod +x configure-vm../configure-vm. VM에 대한 SSH 세션을 종료합니다. 출구 VM의 IP 주소를 가져와서 사용 curl기본 웹 페이지를 보려면 다음을 수행하십시오. curl $(gcloud 컴퓨팅 인스턴스는 vm-base-$NAME_SUFFIX \ --zone $ZONE \ --format="value(networkInterfaces.accessConfigs.[0].natIP를 설명합니다. 다음 예제 출력과 같이 기본 웹 사이트가 반환됩니다. HA / DR 예시

Cloud Storage로의 웜 장애 조치가 있는 Compute Engine 웹사이트에 오신 것을 환영합니다p>

# 기본 VM 이미지 생성 gcloud compute images create image-$NAME_SUFFIX \ --source-disk=vm-base-$NAME_SUFFIX \ --source-disk-zone=$ZONE gcloud compute images create image-disk-$NAME_SUFFIX \ - -source-disk=disk-base-$NAME_SUFFIX \ --source-disk-zone=$ZONE # 인스턴스 템플릿 생성 gcloud compute instance-templates create template-$NAME_SUFFIX-$REGION1 \ --machine-type=n1-standard- 1 \ --subnet=projects/$PROJECT_ID/regions/$REGION1/subnetworks/subnet-$NAME_SUFFIX-$REGION1 \ --region=$REGION1 \ --tags=http-server \ --metadatastartup-script /bin/bashn 'echo\ UUIDblkid\ -s\ UUID\ -o\ 값\ /dev/sdb /var/www/example.com\ ext4\ 폐기,기본값,nofail\ 0\ 2 ee\ -a\ /etc/fstabn'마운트 \ -a \ --image=image-$NAME_SUFFIX \ --create-disk=image=image-disk-$NAME_SUFFIX,auto-delete=yes gcloud compute instance-templates create template-$NAME_SUFFIX-$REGION2 \ --machine -type=n1-standard-1 \ --subnet=projects/$PROJECT_ID/regions/$REGION2/subnetworks/subnet-$NAME_SUFFIX-$REGION2 \ --region=$REGION2 \ --tags=http-server \ --metadatastartup-script /bin/bashn'echo\ UUIDblkid\ -s\ UUID\ -o\ 값\ /dev/sdb /var/www/example.com\ ext4\ 폐기,기본값 ,nofail\ 0\ 2 ee\ -a\ /etc/fstabn'mount\ -a \ --image=image-$NAME_SUFFIX \ --create-disk=image=image-disk-$NAME_SUFFIX,auto-delete=yes # VM 인스턴스에 대한 상태 확인 만들기 gcloud compute health-checks create http-basic-check-$NAME_SUFFIX \ --port 80 # 관리형 인스턴스 그룹 만들기 gcloud compute instance-groups managed create instance-group-$NAME_SUFFIX-$REGION1 \ --template=template-$NAME_SUFFIX-$REGION1 \ --size=2 \ --region=$REGION1 \ --health-check=http-basic-check-$NAME_SUFFIX gcloud compute instance-groups managed create instance-group -$NAME_SUFFIX-$REGION2 \ --template=template-$NAME_SUFFIX-$REGION2 \ --size=2 \ --region=$REGION2 \ --health-check=http-basic-check-$NAME_SUFFIX ## 로드 밸런서 생성 및 구성 사용자가 웹 사이트에 액세스하려면 관리형 인스턴스 그룹에서 실행되는 VM을 통과하는 트래픽을 허용해야 합니다. 또한 관리형 인스턴스 그룹에 영역 오류가 있는 경우 자동으로 트래픽을 새 VM으로 리디렉션하려고 합니다. 다음 섹션에서는 포트 80의 HTTP 트래픽에 대한 백엔드 서비스가 있는 외부 HTTPS 부하 분산기를 만들고, 이전 단계에서 만든 상태 확인을 사용하고, 백엔드 서비스를 통해 외부 IP 주소를 매핑합니다. 자세한 내용은 간단한 외부 HTTP 부하 분산기를 설정하는 방법을 참조하세요. 애플리케이션에 대한 로드 밸런서를 만들고 구성합니다. # HTTP 포트 80에 대한 포트 규칙 구성 gcloud compute instance-groups set-named-ports \ instance-group-$NAME_SUFFIX-$REGION1 \ --named-ports http:80 \ --region $REGION1 gcloud compute instance-groups set- named-ports \ instance-group-$NAME_SUFFIX-$REGION2 \ --named-ports http:80 \ --region $REGION2 # 백엔드 서비스를 만들고 여기에 관리형 인스턴스 그룹을 추가합니다 gcloud compute backend-services create \ web- backend-service-$NAME_SUFFIX \ --protocol=HTTP \ --port-name=http \ --health-checks=http-basic-check-$NAME_SUFFIX \ --global gcloud compute backend-services add-backend \ web- backend-service-$NAME_SUFFIX \ --instance-group=instance-group-$NAME_SUFFIX-$REGION1 \ --instance-group-region=$REGION1 \ --global gcloud compute backend-services add-backend \ web-backend- service-$NAME_SUFFIX \ --instance-group=instance-group-$NAME_SUFFIX-$REGION2 \ --instance-group-region=$REGION2 \ --global # 백엔드 서비스에 대한 URL 맵 생성 gcloud compute url-maps create 웹맵-http-$NAME_SUFFIX \ --default-service web-backend-service-$NAME_SUFFIX # HTTP 트래픽에 대한 전달 구성 gcloud compute target-http-proxies create \ http-lb-proxy-$NAME_SUFFIX \ --url-map web-map-http- $NAME_SUFFIX gcloud compute forwarding-rules create \ http-content-rule-$NAME_SUFFIX \ --global \ --target-http-proxy=http-lb-proxy-$NAME_SUFFIX \ --ports=80 웹 트래픽에 대한 전달 규칙의 IP 주소를 가져옵니다. IP_ADDRESSgcloud compute forwarding-rules describe http-content-rule-$NAME_SUFFIX \ --global \ --format="value(IPAddress 사용 이전 단계에서 로드 밸런서의 IP 주소를 사용하여 웹 사이트를 보려면 curl을 실행하거나 웹 브라우저를 엽니다. 컬 $IP_ADDRESS 부하 분산기가 배포를 완료하고 트래픽을 백엔드로 올바르게 전달하는 데 몇 분 정도 걸립니다. 로드 밸런서가 아직 배포 중인 경우 HTTP 404 오류가 반환됩니다. 필요한 경우 몇 분 정도 기다린 후 웹 사이트에 다시 액세스해 보십시오. 다음 예제 출력과 같이 기본 웹 사이트가 반환됩니다. HA / DR 예시

Cloud Storage로의 웜 장애 조치가 있는 Compute Engine 웹사이트에 오신 것을 환영합니다p>

< index.html HA / DR example

Welcome to a test static web server with warm failover from Cloud Storagep>

example.com Get the details of the Cloud DNS zone: gcloud dns managed-zones describe zone-$NAME_SUFFIX The following example output shows the nameServersfor the zone, such as ns-cloud-b1.googledomains.com kind: dns#managedZone name: zone-app nameServers: - ns-cloud-b1.googledomains.com. - ns-cloud-b2.googledomains.com. - ns-cloud-b3.googledomains.com. - ns-cloud-b4.googledomains.com Cloud DNS must be authoritative for your domain. Create nameserver (NS) records with your domain registrar that point to your Cloud DNS zone. Use the nameserver addresses returned in the previous step For more information and an example using Google Domains, see How to update name servers In your Cloud DNS zone, add a record for wwwusing the load balancer IP address obtained in a previous section: gcloud dns record-sets transaction start \ --zone=zone-$NAME_SUFFIX gcloud dns record-sets transaction add $IP_ADDRESS \ --name=www.$DOMAIN \ --ttl=300 \ --type=A \ --zone=zone-$NAME_SUFFIX This record directs user requests for the website through the load balancer to the managed instance groups. A TTL of 300 seconds is set to reduce the length of time the cached DNS record exists for a user Create a record to be used by the Cloud Storage bucket for the static website: gcloud dns record-sets transaction add c.storage.googleapis.com. \ --name=static-web.$DOMAIN \ --ttl=300 \ --type=CNAME \ --zone=zone-$NAME_SUFFIX This example uses static-webas the subdomain. Leave the c.storage.googleapis.com.Again, a TTL of 300 seconds is set to reduce the length of time the cached DNS record exists for a user Finally,the DNS record additions to the zone: gcloud dns record-sets transaction execute \ --zone=zone-$NAME_SUFFIX ## Verify and test the DNS zone and records Let's review the resource deployments before simulating a zone failure. All of the resources have been created to support the environment, as shown in the following image: - Cloud DNS zone records direct users to the load balancer for distribution across the managed instance group VMs - A Cloud Storage bucket is configured to host static web pages if there's an outage with the managed instance groups - The Cloud DNS zone is configured to use the static site in Cloud Storage, but doesn't currently resolve requests to the storage bucket To view the DNS records and test resolution, you must resolve addresses against the Cloud DNS servers. In production deployments, make sure you test and verify the addresses resolve correctly, then update your own DNS servers to resolve appropriately. This document doesn't detail the steps to update your own DNS servers, only how to verify traffic flows correctly under normal and failover conditions Get the details of the Cloud DNS zone again: gcloud dns managed-zones describe zone-$NAME_SUFFIX The following example output shows the nameServersfor the zone, such as ns-cloud-b1.googledomains.com kind: dns#managedZone name: zone-app nameServers: - ns-cloud-b1.googledomains.com. - ns-cloud-b2.googledomains.com. - ns-cloud-b3.googledomains.com. - ns-cloud-b4.googledomains.com To resolve the wwwrecord for your Cloud DNS zone against one of these name servers, use the digcommand: dig @ns-cloud-b1.googledomains.com www.$DOMAIN This example uses the ns-cloud-b1.googledomains.comnameserver address returned from the previous describecommand. Provide your own nameserver address shown in the output of the previous command The following example output shows that the record resolves to the IP address of the load balancer. If you used this nameserver to access the address, such as using curland the --resolveparameter with the Cloud DNS nameserver, the default page would be displayed from one of the managed instance groups behind the load balancer ;DiG [email protected] www.example.com ; (1 server found);; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 300 IN A 35.227.253.90 Use the digcommand again to verify the DNS record for the static website in Cloud Storage: dig @ns-cloud-b1.googledomains.com static-web.$DOMAIN The following example output shows that the record resolves to Cloud Storage that can serve the static content from the storage bucket: ;DiG [email protected] static-web.example.com ; (1 server found);; QUESTION SECTION: ;static-web.example.com. IN A ;; ANSWER SECTION: static-web.example.com. 300 IN CNAME c.storage.googleapis.com ## Fail over to the Cloud Storage bucket In a production environment, you might get an alert using Cloud Monitoring or other monitoring solution when there's a problem with the managed instance groups. This alert prompts a human to understand the scope of the failure before you update the Cloud DNS records to redirect traffic to the Cloud Storage-hosted static website. An alternative approach is to use your monitoring solution to automatically respond to outages with the managed instance groups When you fail over, Cloud DNS resolves traffic to the Cloud Storage-hosted static website, as shown in the following image: When you or your monitoring solution determine the most appropriate action is to update the Cloud DNS records to direct traffic to Cloud Storage, update the existing DNS A record. In this document, you manually update the Cloud DNS records to redirect traffic to the Cloud Storage-hosted static website To fail over the Cloud DNS records, remove the existing Arecord that resolves to the load balancer: gcloud dns record-sets transaction start \ --zone=zone-$NAME_SUFFIX gcloud dns record-sets transaction remove $IP_ADDRESS \ --name=www.$DOMAIN \ --ttl=300 \ --type=A \ --zone=zone-$NAME_SUFFIX Create a CNAMErecord for wwwthat points to the Cloud Storage-hosted content: gcloud dns record-sets transaction add static-web.$DOMAIN \ --name=www.$DOMAIN. \ --ttl=30 \ --type=CNAME \ --zone=zone-$NAME_SUFFIX the updates to the Cloud DNS zone: gcloud dns record-sets transaction execute \ --zone=zone-$NAME_SUFFIX Use the digcommand to confirm the wwwrecord now resolves to the address of the Cloud Storage static website: dig @ns-cloud-b1.googledomains.com www.$DOMAIN The following example output shows that the www.example.comrecord resolves to the CNAME record of the Cloud Storage static website. Requests to access www.example.comare redirected to the Cloud Storage bucket, which displays the static website: ;DiG [email protected] www.example.com ; (1 server found);; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 30 IN CNAME static-web.example.com. static-web.example.com. 300 IN CNAME c.storage.googleapis.com ## Fail back to the managed instance groups After issues with the managed instance groups are resolved, you can fail back to serving content from the load-balanced managed instance groups by updating the Cloud DNS records again. Again, a human might make this decision using Cloud Monitoring insights for the health of the managed instance groups. Or, you could use automation to respond to the restored health of the managed instance group. In this document, you manually update the Cloud DNS records When you fail back, Cloud DNS resolves traffic to the managed instance groups again, as shown in the following image: Remove the wwwCNAME record that redirects traffic to the Cloud Storage-hosted content: gcloud dns record-sets transaction start \ --zone=zone-$NAME_SUFFIX gcloud dns record-sets transaction remove static-web.$DOMAIN \ --name=www.$DOMAIN \ --ttl=30 \ --type=CNAME \ --zone=zone-$NAME_SUFFIX Add an Arecord to point to the load balancer in front of the managed instance groups again: gcloud dns record-sets transaction add $IP_ADDRESS \ --name=www.$DOMAIN \ --ttl=300 \ --type=A \ --zone=zone-$NAME_SUFFIX the updates to the Cloud DNS zone: gcloud dns record-sets transaction execute \ --zone=zone-$NAME_SUFFIX Use the digcommand one more time to confirm the wwwrecord resolves to the address of the load balancer in front of the managed instance groups again: dig @ns-cloud-b1.googledomains.com www.$DOMAIN The following example output shows that the record resolves to the IP address of the load balancer and traffic would be served from one of the managed instance groups: ;DiG [email protected] www.example.com ; (1 server found);; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 300 IN A 35.227.253.90 ## Clean up To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources To delete the individual resources created in this document, complete the following steps: Delete the DNS zone and records: touch empty-file gcloud dns record-sets import -z zone-$NAME_SUFFIX \ --delete-all-existing \ empty-file rm empty-file gcloud dns managed-zones delete zone-$NAME_SUFFIX Delete the Cloud Storage bucket: gsutil rm -r gsstatic-web.$DOMAIN Delete the load balancer configuration: gcloud compute forwarding-rules delete \ http-content-rule-$NAME_SUFFIX --global --quiet gcloud compute target-http-proxies delete \ http-lb-proxy-$NAME_SUFFIX --quiet gcloud compute url-maps delete web-map-http-$NAME_SUFFIX --quiet gcloud compute backend-services delete \ web-backend-service-$NAME_SUFFIX --global --quiet Delete the managed instance groups and health check: gcloud compute instance-groups managed delete \ instance-group-$NAME_SUFFIX-$REGION1 \ --region=$REGION1 --quiet gcloud compute instance-groups managed delete \ instance-group-$NAME_SUFFIX-$REGION2 \ --region=$REGION2 --quiet gcloud compute health-checks delete http-basic-check-$NAME_SUFFIX --quiet Delete the instance templates, images, base VM, and persistent disks: gcloud compute instance-templates delete \ template-$NAME_SUFFIX-$REGION1 --quiet gcloud compute instance-templates delete \ template-$NAME_SUFFIX-$REGION2 --quiet gcloud compute images delete image-$NAME_SUFFIX --quiet gcloud compute images delete image-disk-$NAME_SUFFIX --quiet gcloud compute instances delete vm-base-$NAME_SUFFIX \ --zone=$ZONE --quiet Delete the firewall rules gcloud compute firewall-rules delete \ allow-health-check-$NAME_SUFFIX --quiet gcloud compute firewall-rules delete \ allow-ssh-$NAME_SUFFIX --quiet gcloud compute firewall-rules delete \ allow-http-$NAME_SUFFIX --quiet Delete the subnet and VPC gcloud compute networks subnets delete \ subnet-$NAME_SUFFIX-$REGION1 --region=$REGION1 --quiet gcloud compute networks subnets delete \ subnet-$NAME_SUFFIX-$REGION2 --region=$REGION2 --quiet gcloud compute networks delete network-$NAME_SUFFIX --quiet ## What's next - For an alternative approach that uses external HTTP(S) Load Balancing instead of Cloud DNS to control the failover, see Deploy a warm recoverable web server with Compute Engine and Cloud Storage. This pattern is useful if you don't have, or don't want to use, Cloud DNS - To learn how how to determine the best approach for your own applications and which recovery method to use, see the Disaster recovery planning guide - To see other patterns for applications, such as cold and hot failover, see Disaster recovery scenarios for applications - For more ways to handle scale and availability, see the Patterns for scalable and resilient apps - Explore reference architectures, diagrams, tutorials, and best practices about Google Cloud. Take a look at our Cloud Architecture Center.