Getting started with Java on Compute Engine

This tutorial shows how to get started with Compute Engine.Follow this tutorial by deploying a Hello World Java webapp to Compute Engine. For help getting started with App Engine, seetheApp Engine standard environment.

Objectives

  • Use Cloud Shell to download and deploy a Hello World sample app.
  • Deploy a Hello World sample app to a single Compute Engine instance.

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use thepricing calculator.

New Google Cloud users might be eligible for afree trial.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Compute Engine API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Compute Engine API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  8. In the Google Cloud console, open the app inCloud Shell.

    Go to Cloud Shell

    Cloud Shell provides command-line access to your cloud resourcesdirectly from the browser.

  9. If you agree to clone the repository, clickConfirm to download the sample code and change into the appdirectory.

  10. In Cloud Shell, configure the gcloud CLI to useyour new Google Cloud project:
    # Configure gcloud for your projectgcloudconfigsetprojectYOUR_PROJECT_ID

Running the app in Cloud Shell

  1. In Cloud Shell, start a local web server:

    mvn-Plocalcleanjetty:run-exploded-DprojectID=YOUR-PROJECT-ID
  2. In Cloud Shell, clickWeb preview,and selectPreview on port 8080. This opens a new windowwith your running app.

    In your web browser, you see some Hello World text, served from yourlocal machine.

  3. When you're ready to move on, stop the local web server by pressingControl+C in Cloud Shell.

Deploying to a single instance

This section walks you through running a single instance of your appon Compute Engine.

Single-instance deployment.

From Cloud Shell, you can deploy to a single Compute Engineinstance virtual machine (VM) which runs your app.

Use a startup script to initialize an instance

You need a way to instruct your instance to download and run your code.An instance can have a startup script that runs whenever the instance isstarted or restarted.

A startup script runs when an instance first boots.

set-eset-v# Talk to the metadata server to get the project idPROJECTID=$(curl-s"http://metadata.google.internal/computeMetadata/v1/project/project-id"-H"Metadata-Flavor: Google")echo"Project ID:${PROJECTID}"# Install dependencies from aptapt-getinstall-yqopenjdk-11-jdkgitmavenmvn--version# Jetty Setupmkdir-p/opt/jetty/tempmkdir-p/var/log/jetty# Get Jettycurl-Lhttps://repo1.maven.org/maven2/org/eclipse/jetty/jetty-distribution/9.4.13.v20181111/jetty-distribution-9.4.13.v20181111.tar.gz-ojetty9.tgztarxfjetty9.tgz--strip-components=1-C/opt/jetty# Add a Jetty Useruseradd--user-group--shell/bin/false--home-dir/opt/jetty/tempjettycd/opt/jetty# Add running as "jetty"java-jar/opt/jetty/start.jar--add-to-startd=setuidcd/# Clone the source repository.gitclonehttps://github.com/GoogleCloudPlatform/getting-started-javacdgetting-started-java/gce# Build the .war file and rename.# very important - by renaming the war to root.war, it will run as the root servlet.mvncleanpackage-qmvtarget/getting-started-gce-1.0-SNAPSHOT.war/opt/jetty/webapps/root.war# Make sure "jetty" owns everything.chown--recursivejetty/opt/jetty# Configure the default paths for the Jetty servicecp/opt/jetty/bin/jetty.sh/etc/init.d/jettyecho"JETTY_HOME=/opt/jetty" >/etc/default/jetty{echo"JETTY_BASE=/opt/jetty"echo"TMPDIR=/opt/jetty/temp"echo"JAVA_OPTIONS=-Djetty.http.port=80"echo"JETTY_LOGS=/var/log/jetty"} >>/etc/default/jetty# Reload daemon to pick up new servicesystemctldaemon-reload# Install logging monitor. The monitor will automatically pickup logs sent to syslog.curl-sSOhttps://dl.google.com/cloudagents/add-logging-agent-repo.shsudobashadd-logging-agent-repo.sh--also-installservicegoogle-fluentdrestart&servicejettystartservicejettycheckecho"Startup Complete"

The startup script performs these tasks:

  • Installs Java 11 and makes it the default version.

  • Installs and configures Jetty.

  • Copies the Java WAR file from the Cloud Storage bucket to Jetty'swebapps and renames itroot.war. This makes it the root servlet, so itdoesn't need to be named in the URL.

  • Installs the Cloud Logging agent and configures it tomonitor the app logs. This means that the loggingconfigured in the previous steps of this tutorial are uploaded just as if youwere using the App Engine flexible environment.

Create and configure a Compute Engine instance

  1. Create a Compute Engine instance:

    gcloudcomputeinstancescreatemy-app-instance
    --image-family=debian-10
    --image-project=debian-cloud
    --machine-type=g1-small
    --scopesuserinfo-email,cloud-platform
    --metadata-from-filestartup-script=gce/startup-script.sh
    --zoneYOUR_ZONE
    --tagshttp-server
    ReplaceYOUR_ZONE with a development zone, for exampleus-central1-a. For more information on regions and zones, seeGeography and regions.

    This creates a new instance, allows it to access Google Cloudservices, and runs your startup script. The instance name ismy-app-instance.

  2. Check the progress of the instance creation:

    gcloud compute instances get-serial-port-output my-app-instance --zoneYOUR_ZONE

    When the startup script is complete, you see the following message:

    startup-script: INFO Finished running startup scripts.
  3. Create a firewall rule to allow traffic to your instance:

    gcloudcomputefirewall-rulescreatedefault-allow-http-80\--allowtcp:80\--source-ranges0.0.0.0/0\--target-tagshttp-server\--description"Allow port 80 access to http-server"

  4. Get the external IP address of your instance:

    gcloudcomputeinstanceslist
  5. To see your app running, enter this URL in your browser:

    http://YOUR_INSTANCE_IP

    ReplaceYOUR_INSTANCE_IP with the external IPaddress of your instance.

Manage and monitor an instance

You can use the Google Cloud console to monitor and manage your instance.

  1. In the Google Cloud console, go to theVM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, clickSSH in the row of the instance that you want to connect to.
  3. To view all of the logs generated by your Compute Engine resources, go to theLogs Explorer page.

    Go to Logs Explorer

    Cloud Logging is automatically configured to gather logs from various common services, includingsyslog.

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.

Delete the project

    Caution: Deleting a project has the following effects:
    • Everything in the project is deleted. If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
    • Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as anappspot.com URL, delete selected resources inside the project instead of deleting the whole project.

    If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.

  1. In the Google Cloud console, go to theManage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then clickDelete.
  3. In the dialog, type the project ID, and then clickShut down to delete the project.

Delete the individual resources

gcloudcomputeinstancesdeletemy-app-instance--zone=YOUR_ZONE--delete-disks=allgcloudcomputefirewall-rulesdeletedefault-allow-http-80

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.