Day 2: Services and Routes
Goal: Publish notes-api under a versioned path, distinguish routes by path, method and host, and read Kong’s error codes. · Duration: approx. 60 min · Prerequisite: Day 1
Briefing
- A service is a backend: protocol, host, port,
optionally a path, plus timeouts and retries.
url:is the shorthand for all four. - A route binds requests to a service, by
paths,methods,hostsorheaders. All specified conditions must match. strip_path: true(the default) strips the matching path before Kong forwards.- If several routes match, the more specific one wins: more conditions, longer prefix.
GET /api/v1/notes ──► Route notes-lesen (GET, /api/v1/notes)
strip_path ─► "" + service path /notes
──► http://notes-api:8080/notes
Drill 1: The First Attempt with notes-api
source ~/kong-lab/setup/env.sh
mkdir -p ~/kong-lab/tag02 && cd ~/kong-lab/kong
cat > kong.yaml <<'EOF'
_format_version: "3.0"
services:
- name: echo
url: http://echo:8080
routes:
- name: echo
paths: [/echo]
- name: notes
url: http://notes-api:8080
routes:
- name: notes
paths: [/notes]
EOF
kreload
curl -si $PROXY/notes | sed -n '1p;$p'
curl -s $ADMIN/routes/notes | jq -c '{paths, strip_path, preserve_host, methods}'Expected (shortened, your IDs and times will differ):
Kong reloaded
HTTP/1.1 404 Not Found
404 page not found
{"paths":["/notes"],"strip_path":true,"preserve_host":false,"methods":null}
A 404, but this time not from Kong:
404 page not found is the response from Go. Kong stripped
/notes and sent / to notes-api. With
strip_path: false, Kong passes the path through
unchanged:
sed -i 's| paths: \[/notes\]|&\n strip_path: false|' kong.yaml
kreload
curl -s $PROXY/notes | jq -c '.[0]'Expected:
Kong reloaded
{"id":"ba87895f-…","text":"vor dem Gateway"}
Tip:
compose.yamlmounts the whole directory~/kong-lab/kong, not justkong.yaml.sed -iand many editors write a new file; a file mounted on its own would then no longer be visible to the container.
Save your progress? Sign up for free
Drill 2: A Versioned Path
To the outside, the API should be called /api/v1/notes;
internally it stays /notes. And reading and writing get
their own routes so that you can protect them differently from Day 5
on:
cat > kong.yaml <<'EOF'
_format_version: "3.0"
services:
- name: echo
url: http://echo:8080
routes:
- name: echo
paths: [/echo]
- name: notes
url: http://notes-api:8080/notes
routes:
- name: notes-lesen
paths: [/api/v1/notes]
methods: [GET]
- name: notes-schreiben
paths: [/api/v1/notes]
methods: [POST]
EOF
kreload
curl -s $PROXY/api/v1/notes | jq -c '.[0]'
curl -s -X POST -H 'X-API-Key: lab-api-key-123' -H 'Content-Type: application/json' \
-d '{"text":"durch Kong"}' $PROXY/api/v1/notes; echoExpected:
Kong reloaded
{"id":"ba87895f-…","text":"vor dem Gateway"}
{"id":"468ee201-…","text":"durch Kong"}
strip_path strips /api/v1/notes, and Kong
appends the rest (nothing) to the service’s path /notes.
This is how you decouple the public URL from the internal one.
Save your progress? Sign up for free
Drill 3: Methods and the Longest Prefix
What happens to DELETE /api/v1/notes? Neither of the two
routes allows DELETE. Add a catch-all route for /api that
leads to the echo service:
cat >> kong.yaml <<'EOF'
- name: api-rest
url: http://echo:8080/anything
routes:
- name: api-rest
paths: [/api]
EOF
kreload
curl -s -X DELETE $PROXY/api/v1/notes | jq -c '{url, method}'
curl -s $PROXY/api/v2/x | jq -c '{url}'
curl -s $PROXY/api/v1/notes | jq -c '.[0].text'Expected:
Kong reloaded
{"url":"http://echo:8080/anything/v1/notes","method":"DELETE"}
{"url":"http://echo:8080/anything/v2/x"}
"vor dem Gateway"
GET still lands at notes-api: /api/v1/notes
is longer than /api and matches more precisely.
DELETE only matches /api and falls through.
The order in the file does not matter.
Save your progress? Sign up for free
Drill 4: Routing by Host
A route without a path, only with a hostname.
preserve_host: true passes the client’s host on to the
backend:
cat > /tmp/host.yaml <<'EOF'
- name: echo-host
hosts: [echo.lab]
preserve_host: true
EOF
sed -i '/ paths: \[\/echo\]/r /tmp/host.yaml' kong.yaml
kreload
curl -s -H 'Host: echo.lab' $PROXY/headers | jq -c '.headers | {Host}'
curl -s $PROXY/echo/headers | jq -c '.headers | {Host, "X-Forwarded-Host"}'
curl -si -H 'Host: andere.lab' $PROXY/headers | head -1Expected:
Kong reloaded
{"Host":["echo.lab"]}
{"Host":["echo:8080"],"X-Forwarded-Host":["localhost"]}
HTTP/1.1 404 Not Found
Without preserve_host, Kong sets the service’s host
(echo:8080) and passes the original one along in
X-Forwarded-Host. Some backends build links with it; then
you need preserve_host.
Save your progress? Sign up for free
Drill 5: Reading Error Codes
Three deliberately broken services: wrong port, unknown name, too slow.
cat >> kong.yaml <<'EOF'
- name: kaputt-port
url: http://notes-api:9999
routes:
- name: kaputt-port
paths: [/kaputt/port]
- name: kaputt-dns
url: http://gibtsnicht:8080
routes:
- name: kaputt-dns
paths: [/kaputt/dns]
- name: langsam
url: http://echo:8080/delay/3
read_timeout: 1000
retries: 0
routes:
- name: langsam
paths: [/langsam]
EOF
kreload
for p in kaputt/port kaputt/dns langsam; do
curl -s -w ' %{http_code}\n' $PROXY/$p | tr -d '\n'; echo
doneExpected (shortened):
Kong reloaded
{ "message":"An invalid response was received from the upstream server", … } 502
{ "message":"name resolution failed", … } 503
{ "message":"The upstream server is timing out", … } 504
| Code | Meaning in Kong |
|---|---|
404 with no Route matched |
no route matches |
| 502 | backend unreachable or answered with nonsense |
| 503 | name cannot be resolved or no healthy target (Day 9) |
| 504 | read_timeout exceeded |
The details are in Kong’s log, with request_id:
docker compose logs kong 2>&1 | grep '\[error\]' | tail -3 | cut -c1-120Expected (shortened):
kong-1 | … [error] … connect() failed (111: Connection refused) while connecting to u…
kong-1 | … [error] … DNS resolution failed: dns server error: 3 name error. Tried: …
kong-1 | … [error] … upstream timed out (110: Connection timed out) while reading res…
Save your progress? Sign up for free
Drill 6: Clean Up and Save the State
The broken services go away, and the API version is added. Today’s state is in the companion code:
cp ~/kong-lab/code/tag02/kong.yaml ~/kong-lab/kong/kong.yaml
docker compose exec kong kong config parse /kong/kong.yaml
kreload
curl -s $ADMIN/routes | jq -r '.data[] | [.name, (.paths // [] | join(",")),
(.methods // [] | join(",")), (.hosts // [] | join(","))] | @tsv' | sortExpected (shortened):
parse successful
Kong reloaded
api-rest /api
echo /echo
echo-host echo.lab
notes-lesen /api/v1/notes GET
notes-schreiben /api/v1/notes POST
notes-version /api/v1/version GET
Save your progress? Sign up for free
Checkpoint
curl -s $PROXY/api/v1/notes | jq lengthExpected: at least two notes, read through Kong.
2
curl -s $ADMIN/services/notes | jq -c '{host, port, path, retries, read_timeout}'Expected: the service with internal path /notes and the
default values.
{"host":"notes-api","port":8080,"path":"/notes","retries":5,"read_timeout":60000}
curl -s -o /dev/null -w '%{http_code}\n' $PROXY/kaputt/portExpected: The broken route no longer exists; /kaputt
matches no route.
404
Challenge
Publish /version of notes-api as
GET /api/v1/version. A POST to the same path
must not reach notes-api. Where does it go instead?
Note: A separate service with path
/version and a route with methods.
Solution
The state from Drill 6 already contains the solution:
- name: notes-version
url: http://notes-api:8080/version
routes:
- name: notes-version
paths:
- /api/v1/version
methods:
- GETcurl -s $PROXY/api/v1/version
curl -s -X POST $PROXY/api/v1/version | jq -c '{url, method}'Expected:
0.2.0
{"url":"http://echo:8080/anything/v1/version","method":"POST"}
The POST falls through to the catch-all route
/api. In production that would be a gap: catch-all routes
lead to a service that cleanly answers 404, not to an echo.
Save your progress? Sign up for free
Enterprise Note
- Router: Kong 3.9 uses
router_flavor = traditional_compatibleby default. Theexpressionsflavor allows rules such ashttp.path ^= "/api" && http.method == "GET"with fixed priorities. - Timeouts: 60 s for connect, read and write are too
long for APIs. Set them per service to match the backend, and use
retriesonly for idempotent calls. - Versioned paths (
/api/v1) in the gateway let you put a v2 on a new service without breaking clients. - Catch-all routes belong on a service that reveals nothing, or should go away.