Create a Cloud Function on GCP Console and Make an HTTP Request to a VM

Abstract: Resolve connectivity issues between GCP Cloud Functions and VMs by configuring network access and implementing secure HTTP requests using Node.js.

Created: 2026-08-15 by
To create a Cloud Function on Google Cloud Platform that sends an HTTP request to a Virtual Machine, you must first ensure the VM is accessible via its external IP address or internal DNS. The Cloud Function requires the gaxios or axios library to handle outgoing requests securely. You configure the function's HTTP trigger to accept calls, then implement logic within the Node.js runtime to construct and send the POST or GET request to the target VM endpoint.

Prerequisites and Network Configuration

Before writing any code, your infrastructure must be correctly configured to allow traffic between the serverless environment and your compute instance. By default, Cloud Functions cannot reach private resources unless they are in the same VPC network and properly routed. For this tutorial, we assume the VM has a static external IP address for simplicity, though internal IPs require Serverless VPC Access configuration.

Ensure your Compute Engine instance is running and listening on a specific port, typically 80 for HTTP or 443 for HTTPS. If you are using a custom port, verify that the firewall rules associated with your VM’s network tag allow inbound traffic from all sources (0.0.0.0/0) or specifically from the Cloud Functions range. A common pitfall is leaving the firewall closed, which results in timeout errors during testing.

If you encounter resolution issues later, such as Troubleshooting ERR_NAME_NOT_RESOLVED Error on Google Cloud Platform, it is often due to misconfigured DNS or incorrect hostnames being passed in the request URL. Always use the full URL including the protocol (http:// or https://) when constructing your request object.

Setting Up the Cloud Function Environment

Navigate to the Cloud Functions section in the Google Cloud Console. Click on "Create Function" and select the second-generation runtime. Choose Node.js 18 or a later supported version as your runtime environment. This ensures compatibility with modern asynchronous libraries like gaxios.

In the "Function name" field, provide a descriptive identifier such as vm-http-trigger. Under the "Trigger" section, select "HTTP". This creates a publicly accessible URL that can be called via standard HTTP methods. You may restrict access by setting "Authentication" to "Allow uninvoked invocations" if you plan to call it from other services without strict IAM checks, but for development, allowing unauthenticated access simplifies the initial setup.

Scroll down to the "Code" editor area. You will see a default skeleton for an HTTP function. Replace the existing code with the implementation detailed below. Before deploying, you must add dependencies. In the "Dependencies" section, click "Add Dependency" and enter gaxios. Alternatively, you can define these in your package.json file if you are uploading a zip archive instead of editing directly in the console.

Implementing the Node.js Logic

The core logic involves importing the HTTP client library and defining the main export function. The function receives an req (request) and res (response) object. We will extract parameters from the query string or body to make the request dynamic.

const gaxios = require('gaxios');

exports.triggerVmRequest = async (req, res) => {
  // Define the target VM URL
  const vmUrl = 'http://YOUR_VM_EXTERNAL_IP:8080/api/data';

  try {
    // Construct the payload
    const payload = {
      message: req.query.message || 'Hello from Cloud Function',
      timestamp: new Date().toISOString()
    };

    // Make the HTTP request
    const response = await gaxios.request({
      url: vmUrl,
      method: 'POST',
      data: payload,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // Respond back to the caller
    res.status(200).send({
      status: 'Success',
      vmResponse: response.data
    });

  } catch (error) {
    console.error('Error communicating with VM:', error);
    res.status(500).send({
      status: 'Error',
      message: 'Failed to reach VM instance'
    });
  }
};

In this snippet, we replace YOUR_VM_EXTERNAL_IP with the actual static IP address of your Compute Engine instance. The gaxios library handles the underlying HTTP transport. It automatically manages retries and timeouts, which is crucial for serverless environments where cold starts might introduce latency. The function waits for the VM to respond before sending a final JSON response back to the original caller.

Deploying and Testing

Click the "Deploy" button in the top right corner of the Cloud Functions page. Wait for the deployment status to turn green. Once deployed, copy the "Function URL" provided in the console details. Open a terminal or a tool like Postman and send a GET request to this URL.

You can pass additional parameters via query strings, for example: https://us-central1-your-project.cloudfunctions.net/vm-http-trigger?message=TestData. Check the logs in the Cloud Logging dashboard to see the execution flow. If the VM is reachable, you should see a 200 OK response. If you receive a timeout, double-check your firewall rules and ensure the VM is actually listening on the specified port.

Frequently Asked Questions

Why does my Cloud Function timeout when calling the VM?

Timeouts usually occur because the VM is not responding quickly enough or the firewall is blocking the connection. Ensure the VM service is active and the firewall allows inbound traffic on the specific port. Also, check that the Cloud Function and VM are in compatible networks or that the VM has a valid external IP.

Can I use internal IP addresses instead of external ones?

Yes, but you must configure Serverless VPC Access. Without this connector, Cloud Functions cannot route traffic to private subnets. If you use an internal IP without VPC Access, the request will fail with a connection refused or timeout error.

How do I handle authentication for the HTTP request?

If your VM requires authentication, include the necessary headers in the gaxios request config. For example, add an Authorization header with a Bearer token or Basic auth credentials. Never hardcode sensitive credentials in the function code; use Secret Manager instead.

What happens if the VM is offline during the request?

The gaxios library will throw an error caught by the catch block. Your function should handle this gracefully by returning a 500 Internal Server Error or a specific failure message to the caller, rather than crashing unexpectedly.

Is it secure to expose Cloud Functions publicly?

Exposing functions publicly increases the attack surface. To secure them, enable "Authentication" in the trigger settings so only authorized users or service accounts can invoke the function. Additionally, use HTTPS URLs exclusively to encrypt data in transit.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More