Kong API Gateway Tutorial

In this article, I will briefly introduce the topic of Kong API Gateway structure , features and installation

Prerequisites: OS Ubuntu, AWS CLI, Docker CE

Kong is a scalable, open source API Middleware. Kong runs in front of any RESTful API and is extended through Plugins

Some of its plugins:

– OAuth 2:0 Authentication
– SSL
– CORS
– Transformation (Request or Response)
– Rate Limiting
– Request Size Limiting

Kong Architecture :

Kong is on top of NGINX built using the openResty framework. Also you can choose one of them Apache Cassandra or PostgreSQL .

How it works :

Below it is a typical request workflow of an API that uses Kong:

When Kong is running, every request being made to the API will hit Kong first, and then it will be proxied to the final API

Installing a Kong database and Kong: We are going to use Docker

For the docker installation part :

sudo apt update

sudo apt install apt-transport-https ca-certificates curl software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"

sudo apt update
sudo apt install docker-ce
sudo systemctl status docker

To run Kong first we need to create docker network and setup PostgreSQL DB (port 5432 need to be exposed.)

The user and database name should be kong, and that should be passed as environment variables to the container

Create a docker network :

$ docker network create kong-network

Note : If you don’t specify the --driver option, the command automatically creates a bridge network for you.

PostgreSQL container:

$ docker run -d --name kong-database \
--network=kong-net \
-p 5432:5432 \
-e "POSTGRES_USER=kong" \
-e "POSTGRES_DB=kong" \
postgres:9.6

Run the migrations :

docker run --rm \
–- network=kong-net
--link kong-database:kong-database \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
kong kong migrations bootstrap

Start Kong Api Gateway :

 $ docker run -d --name kong \ 
--network=kong-net \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
-e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \
-e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
-e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
-e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl" \
-p 8000:8000 \
-p 8443:8443 \
-p 8001:8001 \
-p 8444:8444 \
kong:latest

Curl:

Ports:

Kong makes use of 4 ports.

a- For consumers:

  • 8000 — for incoming HTTP traffic
  • 8443- for incoming HTTPS traffic

b- For Admin:

  • 8001 — for incoming HTTP traffic
  • 8444- for incoming HTTPS traffic