GCP VM Port Forwarding
GCP VM Port Forwarding
Use Google Cloud Identity-Aware Proxy (IAP) to create secure SSH tunnels to your VM instances. IAP handles authentication and encryption, so you can forward ports without exposing your VM to the public internet.
Prerequisites
Before running any of the commands below, ensure the following are in place:
- Enable IAP TCP forwarding in your GCP project (under Security > Identity-Aware Proxy).
- Configure a firewall rule on your VM that allows ingress from the IAP IP range (
35.235.240.0/20) on the ports you need. - Grant the IAM role
roles/iap.tunnelResourceAccessorto your account (or to the service account used bygcloud).
Basic Command
gcloud compute ssh --zone "{ZONE}" "{VM-NAME}" --tunnel-through-iap --project "{PROJECT-ID}" -- -L {LOCAL-PORT}:{REMOTE-HOST}:{REMOTE-PORT}
Parameters
| Parameter | Description |
|---|---|
{ZONE} |
The zone of your VM instance (e.g., us-central1-a). Note: this is a zone, not a region. |
{VM-NAME} |
The name of your Compute Engine instance. |
{PROJECT-ID} |
Your Google Cloud project ID. |
{LOCAL-PORT} |
The port on your local machine to bind to. |
{REMOTE-HOST} |
The host on the remote VM that the service listens on — typically localhost or 127.0.0.1. |
{REMOTE-PORT} |
The port the service is listening on inside the VM. |
Common Use Cases
Database Access
# MySQL / MariaDB — forward remote port 3306 to local port 3306
gcloud compute ssh --zone "us-central1-a" "my-vm" --tunnel-through-iap --project "my-project" -- -L 3306:localhost:3306
# PostgreSQL — forward remote port 5432 to local port 5432
gcloud compute ssh --zone "us-central1-a" "my-vm" --tunnel-through-iap --project "my-project" -- -L 5432:localhost:5432
Web Services
# Access a web application running on port 8080 inside the VM
gcloud compute ssh --zone "us-central1-a" "my-vm" --tunnel-through-iap --project "my-project" -- -L 8080:localhost:8080
Avoiding Port Conflicts
If the remote port is already in use locally, bind to a different local port:
# Forward remote MySQL (3306) to local port 3307
gcloud compute ssh --zone "us-central1-a" "my-vm" --tunnel-through-iap --project "my-project" -- -L 3307:localhost:3306
Tips
- The tunnel remains open for as long as the SSH session is active. Press
Ctrl+Cto close it. - You can forward multiple ports in a single session by repeating the
-Lflag:-L 3306:localhost:3306 -L 5432:localhost:5432. - If
gcloudprompts you to generate an SSH key, allow it — it creates a project-scoped key that works with IAP.