Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active March 2, 2022 12:46
Show Gist options
  • Save montanaflynn/a3a9336384d42188a45e to your computer and use it in GitHub Desktop.
Save montanaflynn/a3a9336384d42188a45e to your computer and use it in GitHub Desktop.
Example of using Kong with DNS

Kong

Kong is a powerful proxy built on nginx. By taking a request and passing it to an upstream server and then returning the result to the client Kong can perform his magic. To know which requests go to which service Kong looks for a Host header to match against. There's a few other ways Kong can match requests to services but for now that's the most basic route. Pun intended.

Start

Assuming everything has been installed and setup, such as dependencies and config files which can be found in the docs, it's time to turn Kong on. The first time Kong runs you'll see some Kong config values and initial migrations to the datastore.

kong start

Add API

Now we can add our APIs and Microservices to Kong. To do that we'll use Kong's RESTful admin API. Let's say you have a service that returns countries in JSON. It's a simple REST API and it's running on port 4444. You own the domain restcountries.io so let's use that as the public_dns.

curl -i -X POST \
 --url http://localhost:8001/apis/ \
 --data 'name=restcountries' \
 --data 'target_url=http://127.0.0.1:4444' \
 --data 'public_dns=restcountries.io'

Verify

Now that it's added we can verify that Kong is serving it by making a request to Kong's proxy and suppyling the Host header which Kong will try to match any APIs with the same as the public_dns to know where to send the request upstream. Here's an example:

curl http://127.0.0.1:8000 -H "host:restcountries.io"

Set DNS

Now most likely you'll not want to add a host header manually with each request, so let's use our domain and have DNS take care of that for us. Set an A record for the domain pointing to your Kong installation. You can also modify kong.yml to use port 80 for the proxy and do a quick kong restart to have the effects take place. Now we can make a request directly to the domain and it will forward the correct Host header.

curl http://restcountries.io
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment