Hello World service

Create a simple Hello World application, package it into a container image, upload the container image to Container Registry, and then deploy the container image to Cloud Run.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

#include <google/cloud/functions/framework.h>
#include <cstdlib>

namespace gcf = ::google::cloud::functions;

auto hello_world_http() {
  return gcf::MakeFunction([](gcf::HttpRequest const& /*request*/) {
    std::string greeting = "Hello ";
    auto const* target = std::getenv("TARGET");
    greeting += target == nullptr ? "World" : target;
    greeting += "\n";

    return gcf::HttpResponse{}
        .set_header("Content-Type", "text/plain")
        .set_payload(greeting);
  });
}

int main(int argc, char* argv[]) {
  return gcf::Run(argc, argv, hello_world_http());
}

Go

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// Sample run-helloworld is a minimal Cloud Run service.
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	log.Print("starting server...")
	http.HandleFunc("/", handler)

	// Determine port for HTTP service.
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("defaulting to port %s", port)
	}

	// Start HTTP server.
	log.Printf("listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	name := os.Getenv("NAME")
	if name == "" {
		name = "World"
	}
	fmt.Fprintf(w, "Hello %s!\n", name)
}

Java

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


package com.example.helloworld;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class HelloworldApplication {

  @Value("${NAME:World}")
  String name;

  @RestController
  class HelloworldController {
    @GetMapping("/")
    String hello() {
      return "Hello " + name + "!";
    }
  }

  public static void main(String[] args) {
    SpringApplication.run(HelloworldApplication.class, args);
  }
}

Node.js

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import express from 'express';
const app = express();

app.get('/', (req, res) => {
  const name = process.env.NAME || 'World';
  res.send(`Hello ${name}!`);
});

const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
  console.log(`helloworld: listening on port ${port}`);
});

PHP

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

<?php

$name = getenv('NAME', true) ?: 'World';
echo sprintf('Hello %s!', $name);

Python

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import os

from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello_world():
    """Example Hello World route."""
    name = os.environ.get("NAME", "World")
    return f"Hello {name}!"


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

Ruby

To authenticate to Cloud Run, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "sinatra"

set :bind, "0.0.0.0"
port = ENV["PORT"] || "8080"
set :port, port

get "/" do
  name = ENV["NAME"] || "World"
  "Hello #{name}!"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.