1. SIGTERM으로 안전하게 종료해야 한다.
참고 https://linuxhandbook.com/sigterm-vs-sigkill/
참고2 https://dev.to/hienngm/graceful-shutdown-in-nestjs-ensuring-smooth-application-termination-4e5n
kill_server.sh를 수정.. -15 파라미터로 변경
pid=$(<nest_server.pid)
echo "stop nest_server (pid is $pid)"
# kill with SIGTERM
kill -15 $pid
# port 3000을 사용하는 pid에 SIGTERM을 보낸다.
# kill -15 $(lsof -i tcp:3000 | awk '{if (NR > 1) print $2}')
rm nest_server.pid
2. SIGTERM 받을 때, 종료 처리
Nest.js의 라이프 사이클 참고 https://docs.nestjs.com/fundamentals/lifecycle-events onApplicationShutdown 에서 뭔가를 하면 좋을 듯..
main.ts
app.enableShutdownHooks([ShutdownSignal.SIGTERM]);
app.service.ts
import { Injectable, OnApplicationShutdown } from "@nestjs/common";
import axios from 'axios';
import { mongoClient } from "./mongo_db";
import { DISCORD_WEBHOOK_URL, IS_PRODUCTION } from "./app.const";
@Injectable()
export class AppService implements OnApplicationShutdown {
async onApplicationShutdown(signal?: string | undefined) {
console.log(`onApplicationShutdown signal=${signal}`);
console.log("mongoClient.close()")
await mongoClient.close();
if (IS_PRODUCTION) {
console.log("Notify shutdown to DISCORD");
await axios.post(DISCORD_WEBHOOK_URL, {content: "API Server shutdown"});
}
console.log("process exists")
}
}