Kong Core Skills
Everything in Kong is a configuration object, and once you can create four of them - a Service, a Route, a Consumer and a Plugin - you can publish a working API. The rest of the course is refinement: adding policies, scaling out, and operating the thing.
This chapter walks through those four objects end to end. You will create a Service that points at an upstream, attach a Route to it, give a Consumer a credential, protect the route with an authentication plugin, and then look at the same configuration written both ways: as Admin API calls, which is how you explore, and as declarative YAML, which is how you ship. By the end you will be able to publish a new API without editing anyone else’s code.
A Service is an upstream address plus the policies for talking to it. Kong 3.x accepts either the decomposed fields or a single url shorthand that fills them in for you.
curl -X POST http://localhost:8001/services \
--data '{
"name": "orders",
"url": "http://orders.internal:8080",
"retries": 3,
"connect_timeout": 5000,
"read_timeout": 60000,
"write_timeout": 60000
}'
The url shorthand is parsed into protocol, host, port and path. The response shows the decomposed form, which is what you will see everywhere else:
{
"id": "0f7d3a2e-8b1c-4f5a-9d2e-1c3b4a5d6e7f",
"name": "orders",
"protocol": "http",
"host": "orders.internal",
"port": 8080,
"retries": 3,
"connect_timeout": 5000,
"read_timeout": 60000,
"write_timeout": 60000,
"enabled": true
}
Two defaults are worth knowing. retries defaults to 5, which is more aggressive than most people expect - Kong will retry a failed upstream request five times before giving up. connect_timeout defaults to 60000 milliseconds, also generous. On a service where a slow response is worse than a failed one, lower both. And if you do not specify a port, Kong assumes 80 for http and 443 for https.
A Route selects requests. It is attached to a Service, and it is the only place where path, host, method and header matching live.
curl -X POST http://localhost:8001/services/orders/routes \
--data '{
"name": "orders-route",
"paths": ["/orders"],
"strip_path": true,
"methods": ["GET", "POST"]
}'
strip_path is the field people get wrong most often. With strip_path: true a request for /orders/42 is forwarded upstream as /42. With strip_path: false the upstream sees /orders/42. Neither is right in general - it depends on what your service expects - so decide it deliberately for each route rather than inheriting a default.
preserve_host controls the same question for the Host header. It defaults to false, meaning the upstream receives the gateway’s own host rather than the one the client sent. Set it to true when the upstream generates absolute URLs or does virtual-host routing.
Routes also match on hosts, on headers (exact name and value pairs), and on methods. And they can use regular expressions:
_format_version: "3.0"
services:
- name: orders
url: http://orders.internal:8080
routes:
- name: orders-by-id
paths:
- ~/orders/[0-9]+$
strip_path: false
A path beginning with ~ is a regular expression. Regular paths are prefix matches, so /orders also matches /orders/42 and /orders/42/items - which is usually what you want for a versioned API.
Consumers are identities for clients. Kong does not know about your human users.
# The consumer
curl -X POST http://localhost:8001/consumers \
--data '{"username": "payments-service"}'
# The credential
curl -X POST http://localhost:8001/consumers/payments-service/key-auth \
--data '{"key": "a3f9c1e28b7d4f6a9c0e5b3d8f1a2c4e"}'
The credential endpoint is plugin-specific, and this is a pattern worth internalising: each authentication plugin exposes its own sub-resource under the consumer. The key-auth plugin uses /consumers/{name}/key-auth, the JWT plugin uses /consumers/{name}/jwt, and basic-auth uses /consumers/{name}/basic-auth. The nested form is shorter and readable; the plural form (/key-auths, /jwts) also works for bulk operations.
A JWT credential carries the secret and the algorithm rather than a single opaque key:
curl -X POST http://localhost:8001/consumers/reporting-service/jwt \
--data '{
"algorithm": "HS256",
"secret": "e4d7c8b9a0f1e2d3c4b5a6978899aabb"
}'
The algorithm field is validated against the full set - HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512 and EdDSA - and it defaults to HS256. If you pick an RSA or ECDSA variant, the credential must also carry an rsa_public_key, and Kong validates that the key actually parses.
Now attach the plugin. Note the scope: attaching to the Service protects every route in front of it, including routes you add later.
curl -X POST http://localhost:8001/services/orders/plugins \
--data '{
"name": "key-auth",
"config": {
"key_names": ["apikey"],
"hide_credentials": true
}
}'
key_names is the header the key is read from, and it defaults to apikey. hide_credentials strips the key from the request before it reaches the upstream, which you want unless the upstream genuinely needs to see it. The plugin also looks in the query string by default; if you would rather it did not, set key_in_query: false.
A request without the header now gets a 401:
curl -i http://localhost:8000/orders
# HTTP/1.1 401 Unauthorized
# {"message":"Unauthorized"}
curl -i http://localhost:8000/orders -H "apikey: a3f9c1e28b7d4f6a9c0e5b3d8f1a2c4e"
# HTTP/1.1 200 OK
Everything above, written the way you would commit it:
_format_version: "3.0"
services:
- name: orders
url: http://orders.internal:8080
routes:
- name: orders-route
paths:
- /orders
strip_path: true
methods:
- GET
- POST
consumers:
- username: payments-service
keyauth_credentials:
- key: a3f9c1e28b7d4f6a9c0e5b3d8f1a2c4e
plugins:
- name: key-auth
service: orders
config:
key_names:
- apikey
hide_credentials: true
The _format_version field is required, and Kong 3.x accepts 1.1, 2.1 and 3.0 - use 3.0. Note that the declarative format nests routes inside their service and credentials inside their consumer, which is a different shape from the flat Admin API.
Validate the file before loading it:
kong config parse kong.yml
kong config parse checks syntax and schema without touching anything. The sibling commands are kong config db_import kong.yml to load it into a database, kong config db_export to write the current database state back out as YAML, and kong config init to generate a starter file.
For database-less mode, point Kong at the file and it loads at startup:
KONG_DATABASE=off \
KONG_DECLARATIVE_CONFIG=./kong.yml \
kong start
The decK tool (deck) adds the workflow around that file - diffing what is live against what is committed, and syncing:
deck gateway diff kong.yml
deck gateway sync kong.yml
deck gateway diff is the command to put in CI. It exits non-zero when the live configuration differs from the file, which is exactly what a drift check wants.
The Admin API is a REST API on port 8001. A handful of endpoints carry you most of the way:
| Endpoint | Purpose |
|---|---|
GET /services | List services |
POST /services | Create a service |
POST /services/{name}/routes | Create a route under a service |
POST /services/{name}/plugins | Attach a plugin to a service |
POST /routes/{name}/plugins | Attach a plugin to a route |
GET /consumers | List consumers |
POST /consumers/{name}/key-auth | Give a consumer an API key |
GET /plugins/enabled | List the plugins this node has loaded |
GET /status | Health and readiness of the node |
Two habits make the Admin API pleasant to use. First, GET /services?tags=team-payments filters by tag, so you can list everything belonging to one team. Second, GET /status is the readiness probe you should point your orchestrator at.
Note that the Admin API is administrative and unauthenticated by default in older setups. In Kong 3.x you should never expose port 8001 outside a trusted network.
When the upstream is more than one host, put it in an Upstream and point the Service at the upstream’s name.
_format_version: "3.0"
upstreams:
- name: orders-pool
algorithm: round-robin
healthchecks:
active:
type: http
http_path: /healthz
healthy:
interval: 10
successes: 2
unhealthy:
interval: 10
http_failures: 3
targets:
- target: orders-1.internal:8080
weight: 100
- target: orders-2.internal:8080
weight: 100
services:
- name: orders
host: orders-pool
port: 8080
routes:
- name: orders-route
paths:
- /orders
The available algorithms are round-robin, consistent-hashing, least-connections and latency. A target’s weight runs from 0 to 65535 and defaults to 100, so weights are relative to each other: two targets with weight 100 each split traffic evenly, while 100 and 300 splits it one to three.
Active health checks poll each target and remove the ones that fail; passive health checks observe real traffic failures and eject a target without a probe. Use active checks when the upstream exposes a health endpoint, and passive checks when it does not.
A partner needs access to your catalog service. They will send their key in a header called X-Partner-Key, they must be limited to sixty requests per minute, and their key must not be visible to the catalog service itself.
Write the declarative configuration for this, and say where each piece attaches and why.
Approach:
Three separate requirements, each of which maps to a different Kong object and a different scope. The trap is the scope: the natural instinct is to attach the authentication plugin to the Service because “it protects the service”, and the rate limit to the Route because “it is about this endpoint”. Both instincts are wrong for this scenario, and the reason is the ordering of plugin execution.
Kong runs plugins in priority order, and the rate-limiting plugin’s priority sits above key-auth’s. That means the rate limit is applied before the credential is validated. If you attach the rate limit to the Service and the authentication to the Route, the rate limiter runs first and counts requests that were never authenticated - so an unauthenticated attacker could exhaust the partner’s quota and cause a legitimate 429 for the partner. Attaching authentication at the Service level and the rate limit at the Route level gets the order right, because the more specific scope wins and the Service-scoped key-auth runs first.
The second trap is hide_credentials. The requirement says the key must not be visible to the catalog service, so it must be true - the default is false, which leaves the header intact on the forwarded request.
Steps:
-
Service
catalogpointing at the upstream. This is the only place the upstream address appears. -
Route on that service with the path the partner uses.
strip_pathshould match what the upstream expects - if the catalog service serves/catalogitself, keep the prefix (strip_path: false). -
Consumer
partner-acmeso the credentials have an identity to belong to. Without a consumer the key-auth plugin cannot look anything up, and without a consumer there is also no identity to attribute rate-limit counters or logs to. -
Key-auth plugin on the Service (not the Route). Scope matters here because of plugin priority: key-auth must run before rate-limiting, and attaching it at the more specific Service scope guarantees that ordering. Attaching it to the Route instead would leave the rate limiter - scoped at Service level - running first.
-
key_names: ["X-Partner-Key"]so the plugin reads the header the partner actually sends. -
hide_credentials: trueso the key is stripped before the request reaches the catalog service. -
Rate-limiting plugin on the Route, scoped to the Route because the limit belongs to this partner’s use of this endpoint, not to the service as a whole.
limit_by: consumerso the sixty requests per minute are counted against the partner’s consumer identity, andminute: 60for the limit itself.limit_by: ipwould be wrong - the partner’s traffic comes from several IP addresses and each would get its own sixty.
Answer:
_format_version: "3.0"
services:
- name: catalog
url: http://catalog.internal:8080
routes:
- name: catalog-partner-route
paths:
- /partner/catalog
strip_path: false
consumers:
- username: partner-acme
keyauth_credentials:
- key: 7d1f9a3c5e8b2d4f6a0c9e7b3d5f1a8c
plugins:
- name: key-auth
service: catalog
config:
key_names:
- X-Partner-Key
hide_credentials: true
- name: rate-limiting
route: catalog-partner-route
config:
minute: 60
limit_by: consumer
| Piece | Attached to | Setting | Why there |
|---|---|---|---|
key-auth | Service catalog | key_names: [X-Partner-Key], hide_credentials: true | Service scope runs it before the Route-scoped rate limiter, so quota is only consumed by authenticated callers; hiding the key satisfies the visibility requirement |
rate-limiting | Route catalog-partner-route | minute: 60, limit_by: consumer | Route scope makes the quota specific to this partner’s use of this endpoint; consumer scope counts one shared budget across the partner’s IPs |
Consumer partner-acme | - | one key-auth credential | Gives the key-auth plugin something to look up and gives the rate limiter the identity to count against |
The decisive detail is the pair of scopes. Authentication at the Service level and rate limiting at the Route level is not decoration - it is what guarantees the quota is spent only by callers who have presented a valid key, instead of being exhausted by anyone at all.
