Skip to content

Developing With Service Discovery

David Killmon edited this page Mar 20, 2020 · 5 revisions

What is Service Discovery?

Service Discovery is a way of letting apps discover and connect with each other. Typically, apps can only talk to each other if they expose a public endpoint - and even then, requests will have to go over the internet. With ECS Service Discovery each application you create is given a private address and DNS name - meaning each app can talk to each other without ever leaving the local network (VPC) and without exposing a public endpoint.

How Do I use Service Discovery?

Service Discovery is enabled for all apps set up using the ECS CLI. We'll show you how to use it by using an example. Imagine we have a project called kudos and two apps, api and front-end.

In this example we'll imagine our front-end app has a public endpoint and wants to call our api app using its service discovery endpoint.

// Calling our api app from the front-end app using Service Discovery
func ServiceDiscoveryGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	endpoint := fmt.Sprintf("http://api.%s/some-request", os.Getenv("ECS_APP_DISCOVERY_ENDPOINT"))
	resp, err := http.Get(endpoint)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	w.WriteHeader(http.StatusOK)
	w.Write(body)
}

The important part is that our front-end app is making a request to our api app through a special endpoint:

endpoint := fmt.Sprintf("http://api.%s/some-request", os.Getenv("ECS_APP_DISCOVERY_ENDPOINT"))

ECS_APP_DISCOVERY_ENDPOINT is a special environment variable that the ECS CLI sets for you when it creates your app. It's of the format {project name}.local - so in this case in our kudos project, the request would be to http://api.kudos.local/some-request. In this case our api app is running on port 80, but if it was running on another port, say 8080, we'd need to include the port in the request, as well http://api.kudos.local:8080/some-request.

When our front-end makes this request, the endpoint api.kudos.local resolves to a private IP address and is routed privately within your VPC.

Clone this wiki locally