Skip to content

Commit a119f5c

Browse files
committed
feat(k8s): gracefull shutdown
1 parent a036032 commit a119f5c

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

app/deployment.yaml

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,29 @@ spec:
1616
- name: training
1717
image: training:v1
1818
imagePullPolicy: IfNotPresent
19+
readinessProbe:
20+
httpGet:
21+
path: /healthz
22+
port: 3000
23+
initialDelaySeconds: 2
24+
periodSeconds: 2
25+
failureThreshold: 2
26+
successThreshold: 1 # default
27+
timeoutSeconds: 1 # default
1928
livenessProbe:
2029
httpGet:
2130
path: /healthz
2231
port: 3000
23-
initialDelaySeconds: 30
24-
timeoutSeconds: 1
32+
initialDelaySeconds: 5
33+
periodSeconds: 10
34+
failureThreshold: 3 # default
35+
successThreshold: 1 # default
36+
timeoutSeconds: 1 # default
2537
ports:
2638
- containerPort: 3000
2739
env:
2840
- name: SHOULD_FAIL_WITHIN
29-
value: "5000"
41+
value: "300000"
3042
- name: REDIS_URI
3143
valueFrom:
3244
secretKeyRef:

app/index.js

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,37 @@
11
const express = require('express')
22
const app = express()
33

4-
let healthy = true
5-
4+
// READINESS_PROBE_DELAY = failureThreshold * periodSeconds * 1000
5+
const READINESS_PROBE_DELAY = 4000
6+
const state = {
7+
isShutdown: false,
8+
healthy: true
9+
}
10+
console.log(process.pid)
611
if(process.env.SHOULD_FAIL_WITHIN) {
7-
setTimeout(() => { healthy = false }, process.env.SHOULD_FAIL_WITHIN)
12+
setTimeout(() => { state.healthy = false }, process.env.SHOULD_FAIL_WITHIN)
813
}
914

15+
process.on('SIGTERM', () => {
16+
state.isShutdown = true
17+
setTimeout( function gracefulShutdown () {
18+
server.close()
19+
// db close
20+
process.exit()
21+
}, READINESS_PROBE_DELAY)
22+
})
23+
1024
app.get('/', (req, res) => res.send('Hello World!'))
1125
app.get('/healthz', (req, res) => {
12-
if(healthy) {
26+
if (state.isShutdown) {
27+
return res.send(503, 'Service is shutting down')
28+
}
29+
30+
if(state.healthy) {
1331
return res.sendStatus(200)
1432
} else {
1533
return res.sendStatus(500)
1634
}
1735
})
1836

19-
app.listen(3000, () => console.log('Example app listening on port 3000!'))
37+
const server = app.listen(3000, () => console.log('Example app listening on port 3000!'))

0 commit comments

Comments
 (0)