Create public uptime checks

This document describes how to create a public uptime check. A public uptime check can issue requests from multiple locations throughout the world to publicly available URLs or Google Cloud resources to see whether the resource responds. For information about how to create uptime checks for private networks, see Create private uptime checks.

Public uptime checks can determine the availability of the following monitored resources:

For links to information about managing and monitoring your uptime checks, see the What's next section of this document.

Before you begin

  • Firewalls that protect your service affect your use of uptime checks.

    • If the resource you are checking isn't publicly available, you must configure the resource's firewall to permit incoming traffic from the uptime-check servers. See List uptime-check server IP addresses to download a list of the IP addresses.
    • If the resource you are checking doesn't have an external IP address, then public uptime checks are unable to reach it. Consider using private uptime checks instead.
  • The uptime check doesn't load page assets or run JavaScript, and the default configuration of an uptime check doesn't include authentication.

    For HTTP and HTTPS, all URL redirects are followed and the final response received by the uptime check is used to evaluate any success criteria. For HTTPS checks, the SSL certificate expiry time is computed based on the server certificate received in the final response.

    To succeed, these conditions must be met:

    • The HTTP status is Success.
    • The data has no required content or the required content is present.
  • When you create an uptime check, you must specify at least three checkers.

    The uptime-check region USA has three checkers. The uptime-check regions EUROPE, SOUTH_AMERICA, and ASIA_PACIFIC each have one checker.

    If you select Global when using the Google Cloud console, or select REGION_UNSPECIFIED when using the API, then uptime checks are issued from all uptime-check regions.

Create an uptime check

This section explains how to create and configure uptime checks.

Console

To create an uptime check by using the Google Cloud console, do the following:

  1. In the console, select Monitoring or click the following button:
    Go to Monitoring
  2. In the navigation pane, select Uptime checks.

  3. Click Create Uptime check.

    Create an uptime check dialog.

  4. Enter a descriptive title for the Uptime check.

  5. Optional: To add user-defined labels to your uptime check, do the following:

    1. Click More metadata options.
    2. Click Key and enter a name for the label. Label names must start with a lowercase letter, and they can contain lowercase letters, numerals, underscores, and dashes. For example, enter severity.
    3. Click Value and enter a value for your label. Label values can contain lowercase letters, numerals, underscores, and dashes. For example, enter critical.
    4. For each additional label, click Add user label and then enter the key and value of the label.
  6. Click Next and specify the target of the uptime check:

    1. Select the protocol. You have the options of HTTP, HTTPS, and TCP.

    2. Choose one of the following resource types:

      • URL: Any IPv4 address or hostname. Path and port are entered separately.
      • Kubernetes LoadBalancer Service: Kubernetes Service of LoadBalancer type.
      • Instance: Compute Engine or AWS EC2 instances.
      • App Engine: App Engine applications (modules).
      • Elastic Load Balancer: AWS load balancer.
    3. Enter the protocol-specific fields:

      • For TCP checks, enter the port.

      • For HTTP and HTTPS checks, you have the option to enter a path within your host or resource. All uptime checks that use these protocols send a request to http://target/path. In this expression, for a URL resource, target is a hostname or IP address. For an App Engine resource, target is a hostname derived from the service name. For instance and load balancer resources, target is an IP address derived from the name you provided for the resource or the group of resources.

        If you leave the path field blank or if you set the value to /, then the request is issued to http://target/.

        To issue an uptime check to the URL resource example.com/tester, set the hostname field to example.com and the path field to /tester.

        Suppose you've deployed a server to App Engine with a dispatcher that supports / and /hello. If you leave the path field empty, then the uptime check is sent to the / handler. To issue the uptime check to the /hello handler, set the value of the path field to /hello.

    4. Enter the resource-specific fields:

      • For URL resources, enter the hostname in the Hostname field. For example, enter example.com.

      • For Kubernetes LoadBalancer Service resources, enter the service name in the Kubernetes service field.

      • For App Engine resources, enter the service name in the Service field.

      • For Elastic Load Balancer and Instance resources, complete the following fields:

        • To issue an uptime check to a single instance or load balancer, in the Applies to field, select Single and then use the menu to select the specific instance or load balancer.
        • To issue an uptime check to a Monitoring group, in the Applies to field, select Group, and then use the menu to select the group name.
    5. Optional: Set how often the uptime check executes by using the Check frequency field.

    6. Optional: To configure checker regions, or to configure SSL certificates, authentication, headers, and ports for HTTP and HTTPS checks, click More target options:

      • Regions: Select the regions where the uptime checks are to receive requests. An uptime check must have at least 3 checkers. There is 1 checker in all regions except the United States, which has 3 checkers. The default setting, Global includes all regions.
      • Request Method: For HTTP checks, select the request method.
      • Body: For HTTP POST checks, enter the URL encoded body; you must do the encoding yourself. For all other checks, leave this field empty.
      • General: Fill this field in to check virtual hosts. This field isn't available for TCP checks.
      • Port: Specify a port number.
      • Custom Headers: Supply custom headers, and encrypt them if desired. Encryption hides the headers' values in the form. Use encryption for headers related to authentication that you don't want visible to others.

      • Authentication: Provide a single username and password. These values are sent as an Authorization header. If you set values here, don't set a separate Authorization header; if you set an Authorization header, don't set values here. Passwords are always hidden in the form. This field isn't available for TCP checks.

      • SSL Certificate Validation: If you selected HTTPS for a URL resource, then by default, the service attempts to connect over HTTPS and validates the SSL certificate. The uptime check fails if a URL has an invalid certificate. Reasons for an invalid certificate include an expired certificate, a self-signed certificate, a certificate with a domain-name mistmach, and a certificate that uses the AIA extension.

        To force an HTTPS uptime check to validate the SSL certificate, ensure that Validate SSL certificates is selected.

        To disable SSL certificate validation, ensure that Validate SSL certificates is clear.

        If you have SSL Certificates with Authority Information Access (AIA) Extensions, then you must disable SSL certificate validation. These types of certificates aren't supported and fail the validation sequence. Typically, the error message is "Responded with SSL handshake Error in 10000 ms".

        You can use the metric monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires to create an alert that notifies you before your certificate expires. For more information, see Sample policies: Uptime-check policy.

        Select Validate SSL certificates checkbox.

    7. Click Next.

  7. Configure the response requirements:

    • Optional: Set a timeout period for the uptime check by using the Response Timeout field. An uptime check fails if no response is received from more than one location within this period.

    • Optional: To configure the uptime check to perform content matching, ensure that the toggle label is Content matching is enabled:

      • Select the Response content match type from the menu of options. This field determines how the response content is compared to the returned data. For example, if the response content is abcd and the content match type is Contains, then the uptime check is successful if the response data contains abcd. The uptime check fails if the response doesn't contain abcd. For more information, see Validate response data.
      • Enter the Response content. This must be a string no longer than 1024 bytes. In the API, this is the ContentMatcher object.
    • Optional: To prevent log entries due to uptime checks, clear Log check failures.

    • For the HTTP uptime checks, configure the acceptable response codes. By default, HTTP uptime checks mark any 2xx response as a successful response.

    • Click Next

  8. Create an alerting policy. When an alerting policy monitors your uptime check, if the uptime fails, then an incident is created and a notification is sent to all notification channels attached to the policy. For example, if you add an email address to the policy, then an email is sent to that address. You can create the alerting policy in this step, or you can create an alerting policy after the check is created.

    We recommend that you create an alerting policy for your uptime check. However, to skip this step, ensure the text of the toggle button is Do not create an alert. Click the button to change the toggle state.

    To create an alerting policy as part of this flow, do the following:

    1. Ensure the toggle button text is Create an alert. Click the button if necessary.

    2. In the name field, enter a name for the alerting policy or use the default name.

    3. To add one or more notification channels to the alerting policy, in the text box labeled Notification channels, click Menu . Select the channels to add and click OK. The notifications channels are grouped alphabetically for each channel type.

      If a notification channel that you want to add to the alerting policy isn't listed, then click Manage notification channels.

      Notification dialog displaying the refresh and manage channels buttons.

      You are taken to the Notification channels window in a new browser tab. Add the notification channels and then return to this tab, click Refresh , and then select the notification channels to add to the alerting policy. For more information, see Notification channels.

    4. Optional: In the duration field, select how long the uptime checks must fail before an incident is created. By default, the alerting policy is configured to create an incident if at least 2 regions report uptime check failures for a duration of 1 minute.

    See Managing policies for information on disabling, editing, and deleting alerting policies.

  9. To verify your uptime check configuration, click Test. If the result isn't what you expect, see Check failures, correct your configuration, and then repeat the verification step.

  10. Click Create. An error message is displayed when you save an uptime check and a required field isn't populated. After you save your changes, the Uptime check created dialog is displayed.

API

Call the projects.uptimeCheckConfigs.create method. Set the method's parameters as follows:

  • parent: Required. This must be the name of the project in which to create the uptime check. Replace PROJECT_ID with your Google Cloud project ID. The format is:

    projects/PROJECT_ID
    
  • The request body must contain an UptimeCheckConfig object for the new uptime check. This page provides information on only a few fields. For complete documentation on this object and its fields, see UptimeCheckConfig:

    • Leave the name field of the configuration object blank. The system sets this field when it constructs the response configuration object.

    • If you are configuring an HTTP or HTTPS check, then you must populate the HttpCheck field of the UptimeCheckConfig object. In this object, set the requestMethod field as GET or POST. If this field is omitted or set to METHOD_UNSPECIFIED, then a GET request is issued.

      If you are configuring a POST request, then complete the contentType and body fields.

The create method returns the UptimeCheckConfig object for the new configuration.

If the created uptime configuration doesn't work as expected, see the Check failures section on this page.

C#

public static object CreateUptimeCheck(string projectId, string hostName,
    string displayName)
{
    // Define a new config.
    var config = new UptimeCheckConfig()
    {
        DisplayName = displayName,
        MonitoredResource = new MonitoredResource()
        {
            Type = "uptime_url",
            Labels = { { "host", hostName } }
        },
        HttpCheck = new UptimeCheckConfig.Types.HttpCheck()
        {
            Path = "/",
            Port = 80,
        },
        Timeout = TimeSpan.FromSeconds(10).ToDuration(),
        Period = TimeSpan.FromMinutes(5).ToDuration()
    };
    // Create a client.
    var client = UptimeCheckServiceClient.Create();
    ProjectName projectName = new ProjectName(projectId);
    // Create the config.
    var newConfig = client.CreateUptimeCheckConfig(
        projectName,
        config,
        CallSettings.FromExpiration(
            Expiration.FromTimeout(
                TimeSpan.FromMinutes(2))));
    Console.WriteLine(newConfig.Name);
    return 0;
}

Java

private static void createUptimeCheck(
    String projectId, String displayName, String hostName, String pathName) throws IOException {
  CreateUptimeCheckConfigRequest request =
      CreateUptimeCheckConfigRequest.newBuilder()
          .setParent(ProjectName.format(projectId))
          .setUptimeCheckConfig(
              UptimeCheckConfig.newBuilder()
                  .setDisplayName(displayName)
                  .setMonitoredResource(
                      MonitoredResource.newBuilder()
                          .setType("uptime_url")
                          .putLabels("host", hostName))
                  .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
                  .setTimeout(Duration.newBuilder().setSeconds(10))
                  .setPeriod(Duration.newBuilder().setSeconds(300)))
          .build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    UptimeCheckConfig config = client.createUptimeCheckConfig(request);
    System.out.println("Uptime check created: " + config.getDisplayName());
  } catch (Exception e) {
    usage("Exception creating uptime check: " + e.toString());
    throw e;
  }
}

Go


// createGet creates an example uptime check on a GET request.
func createGet(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %v", err)
	}
	defer client.Close()
	req := &monitoringpb.CreateUptimeCheckConfigRequest{
		Parent: "projects/" + projectID,
		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
			DisplayName: "new GET uptime check",
			Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{
				MonitoredResource: &monitoredres.MonitoredResource{
					Type: "uptime_url",
					Labels: map[string]string{
						"host": "example.com",
					},
				},
			},
			CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_{
				HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{
					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_GET,
					Path:          "/",
					Port:          80,
				},
			},
			Timeout: &duration.Duration{Seconds: 10},
			Period:  &duration.Duration{Seconds: 300},
		},
	}
	config, err := client.CreateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateUptimeCheckConfig GET: %v", err)
	}
	fmt.Fprintf(w, "Successfully created GET uptime check %q\n", config.GetDisplayName())
	return config, nil
}

// createPost creates an example uptime check on a POST request.
func createPost(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %v", err)
	}
	defer client.Close()
	req := &monitoringpb.CreateUptimeCheckConfigRequest{
		Parent: "projects/" + projectID,
		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
			DisplayName: "new POST uptime check",
			Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{
				MonitoredResource: &monitoredres.MonitoredResource{
					Type: "uptime_url",
					Labels: map[string]string{
						"host": "example.com",
					},
				},
			},
			CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_{
				HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{
					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_POST,
					ContentType:   monitoringpb.UptimeCheckConfig_HttpCheck_URL_ENCODED,
					Path:          "/",
					Port:          80,
					Body:          []byte(base64.URLEncoding.EncodeToString([]byte("key: value"))),
				},
			},
			Timeout: &duration.Duration{Seconds: 10},
			Period:  &duration.Duration{Seconds: 300},
		},
	}
	config, err := client.CreateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateUptimeCheckConfig POST: %v", err)
	}
	fmt.Fprintf(w, "Successfully created POST uptime check %q\n", config.GetDisplayName())
	return config, nil
}

Node.js

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.UptimeCheckServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const hostname = 'mydomain.com';

const request = {
  // i.e. parent: 'projects/my-project-id'
  parent: client.projectPath(projectId),
  uptimeCheckConfig: {
    displayName: 'My Uptime Check',
    monitoredResource: {
      // See the Uptime Check docs for supported MonitoredResource types
      type: 'uptime_url',
      labels: {
        host: hostname,
      },
    },
    httpCheck: {
      path: '/',
      port: 80,
    },
    timeout: {
      seconds: 10,
    },
    period: {
      seconds: 300,
    },
  },
};

// Creates an uptime check config for a GCE instance
const [uptimeCheckConfig] = await client.createUptimeCheckConfig(request);
console.log('Uptime check created:');
console.log(`ID: ${uptimeCheckConfig.name}`);
console.log(`Display Name: ${uptimeCheckConfig.displayName}`);
console.log('Resource: %j', uptimeCheckConfig.monitoredResource);
console.log('Period: %j', uptimeCheckConfig.period);
console.log('Timeout: %j', uptimeCheckConfig.timeout);
console.log(`Check type: ${uptimeCheckConfig.check_request_type}`);
console.log(
  'Check: %j',
  uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
);
console.log(
  `Content matchers: ${uptimeCheckConfig.contentMatchers
    .map(matcher => matcher.content)
    .join(', ')}`
);
console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);

PHP

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\UptimeCheckConfig;
use Google\Api\MonitoredResource;

/**
 * Example:
 * ```
 * create_uptime_check($projectId, 'myproject.appspot.com', 'Test Uptime Check!');
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $hostName
 * @param string $displayName
 */
function create_uptime_check($projectId, $hostName = 'example.com', $displayName = 'New uptime check')
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);

    $monitoredResource = new MonitoredResource();
    $monitoredResource->setType('uptime_url');
    $monitoredResource->setLabels(['host' => $hostName]);

    $uptimeCheckConfig = new UptimeCheckConfig();
    $uptimeCheckConfig->setDisplayName($displayName);
    $uptimeCheckConfig->setMonitoredResource($monitoredResource);

    $uptimeCheckConfig = $uptimeCheckClient->createUptimeCheckConfig(
        $uptimeCheckClient->projectName($projectId),
        $uptimeCheckConfig
    );

    printf('Created an uptime check: %s' . PHP_EOL, $uptimeCheckConfig->getName());
}

Python

def create_uptime_check_config_get(project_name, host_name=None, display_name=None):
    config = monitoring_v3.UptimeCheckConfig()
    config.display_name = display_name or "New GET uptime check"
    config.monitored_resource = {
        "type": "uptime_url",
        "labels": {"host": host_name or "example.com"}
    }
    config.http_check = {
        "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.GET,
        "path": "/",
        "port": 80
    }
    config.timeout = {"seconds": 10}
    config.period = {"seconds": 300}

    client = monitoring_v3.UptimeCheckServiceClient()
    new_config = client.create_uptime_check_config(request={"parent": project_name, "uptime_check_config": config})
    pprint.pprint(new_config)
    return new_config


def create_uptime_check_config_post(project_name, host_name=None, display_name=None):
    config = monitoring_v3.UptimeCheckConfig()
    config.display_name = display_name or "New POST uptime check"
    config.monitored_resource = {
        "type": "uptime_url",
        "labels": {"host": host_name or "example.com"}
    }
    config.http_check = {
        "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.POST,
        "content_type": monitoring_v3.UptimeCheckConfig.HttpCheck.ContentType.URL_ENCODED,
        "body": "foo=bar".encode("utf-8"),
        "path": "/",
        "port": 80
    }
    config.timeout = {"seconds": 10}
    config.period = {"seconds": 300}

    client = monitoring_v3.UptimeCheckServiceClient()
    new_config = client.create_uptime_check_config(request={"parent": project_name, "uptime_check_config": config})
    pprint.pprint(new_config)
    return new_config

Ruby

def create_uptime_check_config project_id: nil, host_name: nil, display_name: nil
  require "google/cloud/monitoring"

  client = Google::Cloud::Monitoring.uptime_check_service
  project_name = client.project_path project: project_id
  config = {
    display_name:       display_name.nil? ? "New uptime check" : display_name,
    monitored_resource: {
      type:   "uptime_url",
      labels: { "host" => host_name.nil? ? "example.com" : host_name }
    },
    http_check:         { path: "/", port: 80 },
    timeout:            { seconds: 10 },
    period:             { seconds: 300 }
  }
  new_config = client.create_uptime_check_config \
    parent:              project_name,
    uptime_check_config: config
  puts new_config.name
  new_config
end

There can be a delay of up to 5 minutes before the uptime check results start to flow into Monitoring. During that time, the uptime check dashboard reports the status as "no data available."

Verify your uptime check

When you create an uptime check in the console, you can test the configuration before saving.

Successful checks

An uptime check is successful if two conditions are true:

  • The HTTP status is Success.
  • The response has no required content or, a search of the response for the required content is successful.

Failed checks

The following are some possible causes of an uptime check failure:

  • Connection Error - Refused: If you are using the default HTTP connection type, check that you have a web server installed that is responding to HTTP requests. A connection error can happen on a new instance if you haven't installed a web server; see the Quickstart for Compute Engine. If you use an HTTPS connection type, you might have to perform additional configuration steps. For firewall issues, see Getting IP addresses.
  • Name or service not found: The host name might be incorrect.
  • 403 Forbidden: The service is returning an error code to the uptime checker. For example, the default Apache web server configuration returns this code under Amazon Linux, but it returns code 200 (Success) under some other Linux versions. See the LAMP tutorial for Amazon Linux or your web server's documentation.
  • 404 Not found: The path might be incorrect.
  • 408 Request timeout, or no response: The port number might be incorrect, the service might not be running, the service might be inaccessible, or the timeout might be too low. Check that your firewall allows traffic from the uptime servers; see Getting IP addresses. The timeout limit is specified as part of the Response Validation options.

What's next