Kong

How to build load balancer for API with Kong API Gateway

Pinterest LinkedIn Tumblr

Before reading this tutorial, if you’re a beginner with Kong, you should read the following articles about Kong to have a mindset about Kong API Gateway:

In this tutorial, we’ll learn how to build a load balancer for API with Kong. For example, if you have 2 servers and want to distribute requests to 2 servers in tune you need to do the following:

  • Create an upstream
  • Add target to the upstream
  • Create API service and related routes use the upstream name as the host of service
# create an upstream
$ curl -X POST http://kong:8001/upstreams \
    --data "name=address.v1.service"

# add two targets to the upstream
$ curl -X POST http://kong:8001/upstreams/address.v1.service/targets \
    --data "target=192.168.34.11:80"
    --data "weight=100"
$ curl -X POST http://kong:8001/upstreams/address.v1.service/targets \
    --data "target=192.168.34.12:80"
    --data "weight=50"

# create an API Service targeting the Blue upstream
$ curl -X POST http://kong:8001/apis/ \
    --data "name=address-service" \
    --data "hosts=address.mydomain.com" \
    --data "upstream_url=http://address.v1.service/address"

If you’re using Konga you need to configure as follow:

Create an upstream

At first, we need to create an upstream and add all servers to the upstream’s target.

In this guide, I will proxy API https://learncode24h.com/api/data1.json via Kong, so I will add target value is learncode24h.com:443. If you have more than one host, you can add more targets. Kong use round-robin algorithm to distribute request between targets. You can specify weight param to adjust load factor between targets.

Add Service

Next, you need to add service and use upstream name as host name of service. In this case, I’ll use path is /api because /api is the base path of the target API.

Add routes

Now, we’ll add routes for api-lb-service. Suppose I want access kong-host:8000/gateway/data1.json will forward request to learncode24h API, so I will configure paths is /gateway. And don’t forget to set methods to GET value.

Now we can test API by accessing http://localhost:8000/gateway/data1.json, if successful you will receive a response like this.

I'm a full stack developer. I have experiences with Java, Android, PHP, Python, C#, Web development...I hope website https://learncode24h.com will help everyone can learn code within 24h and apply it in working easily.

Comments are closed.