I'm trying to find a way to listen in Deno for the Docker SIGTERM signal to close my Oak server. I got this code from Oak website and it works fine when I call the controller.abort() function, using setTimeout or an end-point. However, I want to call it when I got a SIGTERM signal from Docker and I cannot figure out how to listen for it.
const controller = new AbortController();
const app = new Application();
app.addEventListener("listen", ({ hostname, port }) => {
console.log(
bold("Start listening on ") + yellow(`${hostname}:${port}`),
);
});
// Utilise the signal from the controller
const { signal } = controller;
await app.listen({ hostname: "127.0.0.1", port: 8000, signal });
console.log(bold("Finished."));
I try to use this code from Deno GitHub discussions but also did not work
(() => {
for await (const _ of Deno.signal(Deno.Signal.SIGINT)) {
console.log("interrupt signal")
}
})()
(() => {
for await (const _ of Deno.signal(Deno.Signal.SIGQUIT)) {
console.log("quit signal")
}
})()
(() => {
for await (const _ of Deno.signal(Deno.Signal.SIGTERM)) {
console.log("terminate signal")
}
})()
I don't see either the logs and abort does not get called
Your direction is right but you can simplify your solution.
Example of my application server handler. I am using Opine but it can be adapted by pasting anywhere into your server initialisation. You can try plug it into listener as well.
const handle = onSignal(Deno.Signal.SIGTERM, () => {
mongoConnector.close()
handle.dispose()
})
Reference to Signals Deno STD documentation.
Came across this while looking into the same thing! There's a relatively new unstable feature for adding listeners with addSignalListener.
A working example for Oak:
import { Application } from "https://deno.land/x/oak/mod.ts";
const controller = new AbortController();
const app = new Application();
app.use(() => void console.log('hello!'));
app.listen({port: 8080, signal: controller.signal});
Deno.addSignalListener('SIGTERM', () => {
console.log('Aborting for SIGTERM')
controller.abort();
});
Deno.addSignalListener('SIGINT', () => {
console.log('Aborting for SIGINT')
controller.abort();
});
Can be run with deno run --unstable --allow-net <file>.ts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With