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 web app to Compute Engine. For help getting started with App Engine, see the App Engine standard environment.


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


Neste tutorial, usamos os seguintes componentes faturáveis do Google Cloud Platform:

Para gerar uma estimativa de custo baseada na projeção de uso deste tutorial, use a calculadora de preços. Usuários novos do GCP podem estar qualificados para uma avaliação gratuita.

Before you begin

  1. Faça login na sua Conta do Google.

    Se você ainda não tiver uma, inscreva-se.

  2. No Console do GCP, na página do seletor de projetos, selecione ou crie um projeto do GCP.

    Acesse a página do seletor de projetos

  3. Verifique se o faturamento foi ativado no projeto do Google Cloud Platform. Saiba como confirmar que o faturamento está ativado para seu projeto.

  4. Ative a(s) Compute Engine API necessária(s).

    Ativar a(s) API

  5. In the Google Cloud Console, open the app in Cloud Shell.

    Go to Cloud Shell

    Cloud Shell provides command-line access to your cloud resources directly from the browser. Open Cloud Shell in your browser and click Proceed to download the sample code and change into the app directory.

  6. In Cloud Shell, configure the gcloud tool to use your new Google Cloud project:
    # Configure gcloud for your project
    gcloud config set project YOUR_PROJECT_ID

Running the app in Cloud Shell

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

    mvn -Plocal clean jetty:run-exploded -DprojectID=YOUR-PROJECT-ID
  2. In Cloud Shell, click Web preview , and select Preview on port 8080. This opens a new window with your running app.

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

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

Deploying to a single instance

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

Single-instance deployment.

From Cloud Shell, you can deploy to a single Compute Engine instance 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 is started or restarted.

A startup script runs when an instance first boots.

set -e
set -v

# Talk to the metadata server to get the project id
PROJECTID=$(curl -s "" -H "Metadata-Flavor: Google")

echo "Project ID: ${PROJECTID}"

# Install dependencies from apt
apt-get install -yq openjdk-11-jdk git maven

mvn --version

# Jetty Setup
mkdir -p /opt/jetty/temp
mkdir -p /var/log/jetty

# Get Jetty
curl -L -o jetty9.tgz
tar xf jetty9.tgz  --strip-components=1 -C /opt/jetty

# Add a Jetty User
useradd --user-group --shell /bin/false --home-dir /opt/jetty/temp jetty

cd /opt/jetty
# Add running as "jetty"
java -jar /opt/jetty/start.jar --add-to-startd=setuid
cd /

# Clone the source repository.
git clone
cd getting-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.
mvn clean package -q
mv target/getting-started-gce-1.0-SNAPSHOT.war /opt/jetty/webapps/root.war

# Make sure "jetty" owns everything.
chown --recursive jetty /opt/jetty

# Configure the default paths for the Jetty service
cp /opt/jetty/bin/ /etc/init.d/jetty
echo "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 service
systemctl daemon-reload

# Install logging monitor. The monitor will automatically pickup logs sent to syslog.
curl -s "" | bash
service google-fluentd restart &

service jetty start
service jetty check

echo "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's webapps and renames it root.war. This makes it the root servlet, so it doesn't need to be named in the URL.

  • Installs the Stackdriver Logging agent and configures it to monitor the app logs. This means that the logging configured in the previous steps of this tutorial are uploaded just as if you were using the App Engine flexible environment.

Create and configure a Compute Engine instance

  1. Create a Compute Engine instance:

    gcloud compute instances create my-app-instance 
    --scopes userinfo-email,cloud-platform
    --metadata-from-file startup-script=gce/
    --zone YOUR_ZONE
    --tags http-server
    Replace YOUR_ZONE with a development zone, for example us-central1-a. For more information on regions and zones, see Geography and regions.

    This creates a new instance, allows it to access Google Cloud services, and runs your startup script. The instance name is my-app-instance.

  2. Check the progress of the instance creation:

    gcloud compute instances get-serial-port-output my-app-instance --zone YOUR_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:

    gcloud compute firewall-rules create default-allow-http-80 \
        --allow tcp:80 \
        --source-ranges \
        --target-tags http-server \
        --description "Allow port 80 access to http-server"

  4. Get the external IP address of your instance:

    gcloud compute instances list
  5. To see your app running, enter this URL in your browser:


    Replace YOUR_INSTANCE_IP with the external IP address of your instance.

Manage and monitor an instance

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

  1. No Console do GCP, acesse a página Instâncias de VMs.

    Acessar a página "Instâncias de VMs"

  2. Na lista de instâncias de máquina virtual, clique em SSH na linha da instância à qual você quer se conectar.
  3. To view all of the logs generated by your Compute Engine resources, go to the Logs viewer page. Go to Logs viewer

    Stackdriver Logging is automatically configured to gather logs from various common services, including syslog.

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Delete the project

  1. No Console do GCP, acesse a página Gerenciar recursos.

    Acessar a página Gerenciar recursos

  2. Na lista de projetos, selecione o projeto que você quer excluir e clique em Excluir .
  3. Na caixa de diálogo, digite o ID do projeto e clique em Encerrar para excluí-lo.

Delete the individual resources

gcloud compute instances delete my-app-instance --zone=YOUR_ZONE --delete-disks=all
gcloud compute firewall-rules delete default-allow-http-80

What's next

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…