Skip to content

Commit 6f1aa9c

Browse files
committed
document shutdown of http server
1 parent 1ed3925 commit 6f1aa9c

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

content/faq/multiple-servers.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,41 @@ const app = await NestFactory.create(
3939
);
4040
await app.init();
4141

42-
http.createServer(server).listen(3000);
43-
https.createServer(httpsOptions, server).listen(443);
42+
const httpServer = http.createServer(server).listen(3000);
43+
const httpsServer = https.createServer(httpsOptions, server).listen(443);
44+
```
45+
46+
Because we called `http.createServer` / `https.createServer` ourselves, NestJS doesn't close them when calling `app.close` / on termination signal. We need to do this ourselves:
47+
48+
```typescript
49+
@Injectable()
50+
export class ShutdownObserver implements OnApplicationShutdown {
51+
private httpServers: http.Server[] = [];
52+
53+
public addHttpServer(server: http.Server): void {
54+
this.httpServers.push(server);
55+
}
56+
57+
public async onApplicationShutdown(): Promise<void> {
58+
await Promise.all(
59+
this.httpServers.map((server) =>
60+
new Promise((resolve, reject) => {
61+
server.close((error) => {
62+
if (error) {
63+
reject(error);
64+
} else {
65+
resolve(null);
66+
}
67+
});
68+
})
69+
),
70+
);
71+
}
72+
}
73+
74+
const shutdownObserver = app.get(ShutdownObserver);
75+
shutdownObserver.addHttpServer(httpServer);
76+
shutdownObserver.addHttpServer(httpsServer);
4477
```
4578

4679
> info **Hint** The `ExpressAdapter` is imported from the `@nestjs/platform-express` package. The `http` and `https` packages are native Node.js packages.

0 commit comments

Comments
 (0)