GLBC

A word to the wise

Please read the beta limitations doc to before using this controller. In summary:

This is a work in progress.

It relies on a beta Kubernetes resource.

The loadbalancer controller pod is not aware of your GCE quota.

Overview

A reminder on GCE L7: Google Compute Engine does not have a single resource that represents a L7 loadbalancer. When a user request comes in, it is first handled by the global forwarding rule, which sends the traffic to an HTTP proxy service that sends the traffic to a URL map that parses the URL to see which backend service will handle the request. Each backend service is assigned a set of virtual machine instances grouped into instance groups.

A reminder on Services: A Kubernetes Service defines a set of pods and a means by which to access them, such as single stable IP address and corresponding DNS name. This IP defaults to a cluster VIP in a private address range. You can direct ingress traffic to a particular Service by setting its Type to NodePort or LoadBalancer. NodePort opens up a port on every node in your cluster and proxies traffic to the endpoints of your service, while LoadBalancer allocates an L4 cloud loadbalancer.

What is an Ingress Controller?

Configuring a webserver or loadbalancer is harder than it should be. Most webserver configuration files are very similar. There are some applications that have weird little quirks that tend to throw a wrench in things, but for the most part you can apply the same logic to them and achieve a desired result.

The Ingress resource embodies this idea, and an Ingress controller is meant to handle all the quirks associated with a specific "class" of Ingress (be it a single instance of a loadbalancer, or a more complicated setup of frontends that provide GSLB, DDoS protection, etc).

An Ingress Controller is a daemon, deployed as a Kubernetes Pod, that watches the apiserver's /ingresses endpoint for updates to the Ingress resource. Its job is to satisfy requests for Ingresses.

L7 Load balancing on Kubernetes

To achieve L7 loadbalancing through Kubernetes, we employ a resource called Ingress. The Ingress is consumed by this loadbalancer controller, which creates the following GCE resource graph:

The controller (glbc) manages the lifecycle of each component in the graph. It uses the Kubernetes resources as a spec for the desired state, and the GCE cloud resources as the observed state, and drives the observed to the desired. If an edge is disconnected, it fixes it. Each Ingress translates to a new GCE L7, and the rules on the Ingress become paths in the GCE Url Map. This allows you to route traffic to various backend Kubernetes Services through a single public IP, which is in contrast to Type=LoadBalancer, which allocates a public IP per Kubernetes Service. For this to work, the Kubernetes Service must have Type=NodePort.

The Ingress

An Ingress in Kubernetes is a REST object, similar to a Service. A minimal Ingress might look like:

POSTing this to the Kubernetes API server would result in glbc creating a GCE L7 that routes all traffic sent to http://ip-of-loadbalancer/hostless to :80 of the service named test. If the service doesn't exist yet, or doesn't have a nodePort, glbc will allocate an IP and wait till it does. Once the Service shows up, it will create the required path rules to route traffic to it.

Lines 1-4: Resource metadata used to tag GCE resources. For example, if you go to the console you would see a url map called: k8-fw-default-hostlessendpoint, where default is the namespace and hostlessendpoint is the name of the resource. The Kubernetes API server ensures that namespace/name is unique so there will never be any collisions.

Lines 5-7: Ingress Spec has all the information needed to configure a GCE L7. Most importantly, it contains a list of rules. A rule can take many forms, but the only rule relevant to glbc is the http rule.

Lines 8-9: Each http rule contains the following information: A host (eg: foo.bar.com, defaults to * in this example), a list of paths (eg: /hostless) each of which has an associated backend (test:80). Both the host and path must match the content of an incoming request before the L7 directs traffic to the backend.

Lines 10-12: A backend is a service:port combination. It selects a group of pods capable of servicing traffic sent to the path specified in the parent rule. The port is the desired spec.ports[*].port from the Service Spec -- Note, though, that the L7 actually directs traffic to the corresponding NodePort.

Global Parameters: For the sake of simplicity the example Ingress has no global parameters. However, one can specify a default backend (see examples below) in the absence of which requests that don't match a path in the spec are sent to the default backend of glbc.

Load Balancer Management

You can manage a GCE L7 by creating/updating/deleting the associated Kubernetes Ingress.

Creation

Before you can start creating Ingress you need to start up glbc. We can use the rc.yaml in this directory:

It needs a service with a node port to use as the default backend. This is the backend that's used when an Ingress does not specify the default.

It has an intentionally long terminationGracePeriod, this is only required with the --delete-all-on-quit flag (see Deletion)

Don't start 2 instances of the controller in a single cluster, they will fight each other.

The loadbalancer controller will watch for Services, Nodes and Ingress. Nodes already exist (the nodes in your cluster). We need to create the other 2. You can do so using the ingress-app.yaml in this directory.

A couple of things to note about the Ingress:

It creates a Replication Controller for a simple echoserver application, with 1 replica.

It creates 3 services for the same application pod: echoheaders[x, y, default]

It creates an Ingress with 2 hostnames and 3 endpoints (foo.bar.com{/foo} and bar.baz.com{/foo, /bar}) that access the given service

Go to your GCE console and confirm that the following resources have been created through the HTTPLoadbalancing panel:

A Global Forwarding Rule

An UrlMap

A TargetHTTPProxy

BackendServices (one for each Kubernetes nodePort service)

An Instance Group (with ports corresponding to the BackendServices)

The HTTPLoadBalancing panel will also show you if your backends have responded to the health checks, wait till they do. This can take a few minutes. If you see Health status will display here once configuration is complete. the L7 is still bootstrapping. Wait till you have Healthy instances: X. Even though the GCE L7 is driven by our controller, which notices the Kubernetes healthchecks of a pod, we still need to wait on the first GCE L7 health check to complete. Once your backends are up and healthy:

Updates

Say you don't want a default backend and you'd like to allow all traffic hitting your loadbalancer at /foo to reach your echoheaders backend service, not just the traffic for foo.bar.com. You can modify the Ingress Spec:

spec:
rules:
- http:
paths:
- path: /foo..

and replace the existing Ingress (ignore errors about replacing the Service, we're using the same .yaml file but we only care about the Ingress):

$ kubectl replace -f ingress-app.yaml
ingress "echomap" replaced
$ curl http://107.178.254.239/foo
CLIENT VALUES:
client_address=('10.240.143.179', 59546) (10.240.143.179)
command=GET
path=/foo
real path=/foo
...
$ curl http://107.178.254.239/
<pre>
INTRODUCTION
============
This is an nginx webserver for simple loadbalancer testing. It works well
for me but it might not have some of the features you want. If you would
...

A couple of things to note about this particular update:

An Ingress without a default backend inherits the backend of the Ingress controller.

A IngressRule without a host gets the wildcard. This is controller specific, some loadbalancer controllers do not respect anything but a DNS subdomain as the host. You cannot set the host to a regex.

You never want to delete then re-create an Ingress, as it will result in the controller tearing down and recreating the loadbalancer.

Unexpected updates: Since glbc constantly runs a control loop it won't allow you to break links that black hole traffic. An easy link to break is the url map itself, but you can also disconnect a target proxy from the urlmap, or remove an instance from the instance group (note this is different from deleting the instance, the loadbalancer controller will not recreate it if you do so). Modify one of the url links in the map to point to another backend through the GCE Control Panel UI, and wait till the controller sync (this happens as frequently as you tell it to, via the --resync-period flag). The same goes for the Kubernetes side of things, the API server will validate against obviously bad updates, but if you relink an Ingress so it points to the wrong backends the controller will blindly follow.

Paths

Till now, our examples were simplified in that they hit an endpoint with a catch-all path regex. Most real world backends have subresources. Let's create service to test how the loadbalancer handles paths:

You can put the nodeip:port into your browser and play around with the endpoints so you're familiar with what to expect. We will test the /hostname and /fs/files/nginx.html endpoints. Modify/create your Ingress:

Note what just happened, the endpoint exposes /hostname, and the loadbalancer forwarded the entire matching url to the endpoint. This means if you had '/foo' in the Ingress and tried accessing /hostname, your endpoint would've received /foo/hostname and not known how to route it. Now update the Ingress to access static content via the /fs endpoint:

As before, wait a while for the update to take effect, and try accessing loadbalancerip/fs/files/nginx.html.

Deletion

Most production loadbalancers live as long as the nodes in the cluster and are torn down when the nodes are destroyed. That said, there are plenty of use cases for deleting an Ingress, deleting a loadbalancer controller, or just purging external loadbalancer resources altogether. Deleting a loadbalancer controller pod will not affect the loadbalancers themselves, this way your backends won't suffer a loss of availability if the scheduler pre-empts your controller pod. Deleting a single loadbalancer is as easy as deleting an Ingress via kubectl:

Note that it takes ~30 seconds to purge cloud resources, the API calls to create and delete are a onetime cost. GCE BackendServices are ref-counted and deleted by the controller as you delete Kubernetes Ingress'. This is not sufficient for cleanup, because you might have deleted the Ingress while glbc was down, in which case it would leak cloud resources. You can delete the glbc and purge cloud resources in 2 more ways:

The dev/test way: If you want to delete everything in the cloud when the loadbalancer controller pod dies, start it with the --delete-all-on-quit flag. When a pod is killed it's first sent a SIGTERM, followed by a grace period (set to 10minutes for loadbalancer controllers), followed by a SIGKILL. The controller pod uses this time to delete cloud resources. Be careful with --delete-all-on-quit, because if you're running a production glbc and the scheduler re-schedules your pod for some reason, it will result in a loss of availability. You can do this because your rc.yaml has:

You just instructed the loadbalancer controller to quit, however if it had done so, the replication controller would've just created another pod, so it waits around till you delete the rc.

Health checks

Currently, all service backends must satisfy either of the following requirements to pass the HTTP(S) health checks sent to it from the GCE loadbalancer:

Respond with a 200 on '/'. The content does not matter.

Expose an arbitrary url as a readiness probe on the pods backing the Service.

The Ingress controller looks for a compatible readiness probe first, if it finds one, it adopts it as the GCE loadbalancer's HTTP(S) health check. If there's no readiness probe, or the readiness probe requires special HTTP headers, the Ingress controller points the GCE loadbalancer's HTTP health check at '/'. This is an example of an Ingress that adopts the readiness probe from the endpoints as its health check.

Frontend HTTPS

For encrypted communication between the client to the load balancer, you can secure an Ingress by specifying a secret that contains a TLS private key and certificate. Currently the Ingress only supports a single TLS port, 443, and assumes TLS termination. This controller does not support SNI, so it will ignore all but the first cert in the TLS configuration section. The TLS secret must contain keys named tls.crt and tls.key that contain the certificate and private key to use for TLS, eg:

This creates 2 GCE forwarding rules that use a single static ip. Both :80 and :443 will direct traffic to your backend, which serves HTTP requests on the target port mentioned in the Service associated with the Ingress.

Backend HTTPS

For encrypted communication between the load balancer and your Kubernetes service, you need to decorate the service's port as expecting HTTPS. There's an alpha Service annotation for specifying the expected protocol per service port. Upon seeing the protocol as HTTPS, the ingress controller will assemble a GCP L7 load balancer with an HTTPS backend-service with a HTTPS health check.

The annotation value is a stringified JSON map of port-name to "HTTPS" or "HTTP". If you do not specify the port, "HTTP" is assumed.

Redirecting HTTP to HTTPS

To redirect traffic from :80 to :443 you need to examine the x-forwarded-proto header inserted by the GCE L7, since the Ingress does not support redirect rules. In nginx, this is as simple as adding the following lines to your config:

Note that the GCLB health checks do not get the 301 because they don't include x-forwarded-proto.

Blocking HTTP

You can block traffic on :80 through an annotation. You might want to do this if all your clients are only going to hit the loadbalancer through https and you don't want to waste the extra GCE forwarding rule, eg:

Troubleshooting:

This controller is complicated because it exposes a tangled set of external resources as a single logical abstraction. It's recommended that you are at least aware of how one creates a GCE L7 without a kubernetes Ingress. If weird things happen, here are some basic debugging guidelines:

<a href=//www.google.com/><span id=logo aria-label=Google></span></a>
<p><b>404.</b> <ins>That’s an error.</ins>
<p>The requested URL <code>/hostless</code> was not found on this server. <ins>That’s all we know.</ins>

It means you have lost your IP somehow, or just typed in the wrong IP.

If you see requests taking an abnormal amount of time, run the echoheaders pod and look for the client address

Then head over to the GCE node with internal ip 10.240.29.196 and check that the Service is functioning as expected. Remember that the GCE L7 is routing you through the NodePort service, and try to trace back.

Check if you can access the backend service directly via nodeip:nodeport

Check the GCE console

Make sure you only have a single loadbalancer controller running

Make sure the initial GCE health checks have passed

A crash loop looks like:

$ kubectl get pods
glbc-fjtlq 0/1 CrashLoopBackOff 17 1h

If you hit that it means the controller isn't even starting. Re-check your input flags, especially the required ones.

Creating the firewall rule for GLBC health checks

A default GKE/GCE cluster needs at least 1 firewall rule for GLBC to function. The Ingress controller should create this for you automatically. You can also create it thus:

GLBC Implementation Details

For the curious, here is a high level overview of how the GCE LoadBalancer controller manages cloud resources.

The controller manages cloud resources through a notion of pools. Each pool is the representation of the last known state of a logical cloud resource. Pools are periodically synced with the desired state, as reflected by the Kubernetes api. When you create a new Ingress, the following happens:

Create BackendServices for each Kubernetes backend in the Ingress, through the backend pool.

Add nodePorts for each BackendService to an Instance Group with all the instances in your cluster, through the instance pool.

Periodically, each pool checks that it has a valid connection to the next hop in the above resource graph. So for example, the backend pool will check that each backend is connected to the instance group and that the node ports match, the instance group will check that all the Kubernetes nodes are a part of the instance group, and so on. Since Backends are a limited resource, they're shared (well, everything is limited by your quota, this applies doubly to backend services). This means you can setup N Ingress' exposing M services through different paths and the controller will only create M backends. When all the Ingress' are deleted, the backend pool GCs the backend.

Wish list:

More E2e, integration tests

Better events

Detect leaked resources even if the Ingress has been deleted when the controller isn't around

Specify health checks (currently we just rely on kubernetes service/pod liveness probes and force pods to have a / endpoint that responds with 200 for GCE)