Nodemon 在 Windows Docker 环境中不重启

Nodemon Doesn't Restart in Windows Docker Environment

我的目标是设置一个 Docker 容器,当从主机检测到文件更改时自动重启 NodeJS 服务器。

我选择了 nodemon 来监视文件的变化。

在 Linux 和 Mac 环境中,nodemon 和 docker 运行完美。

然而,当我在 Windows 环境 中时,nodemon 不会重新启动服务器。

文件在主机上更新,并使用我的 docker-compose.yml 文件中的 volumes 参数进行链接。

当我 运行 docker exec <container-name> cat /path/to/fileChanged.js 时,我可以看到文件已更改。这样我就知道文件已正确链接并已在容器中进行了修改。

nodemon 没有为 Windows 重启服务器有什么原因吗?

使用 nodemon --legacy-watch 轮询文件更改而不是侦听文件系统事件。

VirtualBox doesn't pass file system events over the vboxfs share 到您的 Linux 虚拟机。如果您将 Docker 用于 Windows,那么 HyperV 似乎也不会传播文件系统事件。

作为 2021 年的旁注,Docker Mac/Windows 用于将本地文件装载到 VM 的新 GRPCfuse 文件系统现在应该发送文件系统事件。

2022 注:看起来 Windows/WSL Docker 不会将 FS 事件共享到 Linux 虚拟机(请参阅评论@Mohamed Mirghani 和@Ryan Wheale)。

很简单,根据doc你必须改成:

nodemon server.js

至:

nodemon --legacy-watch server.js

这是 Windows 的 docker 中的一个问题。现在已修复

https://www.docker.com/blog/new-filesharing-implementation-in-docker-desktop-windows/

正如其他人所提到的,使用 node --legacy-watch 是可行的,但是,默认的轮询率对您的 cpu 来说相当费力。就我而言,它仅通过遍历我项目中的所有文件就消耗了我 CPU 的 30%。我建议您指定 @Sandokan El Cojo 提到的轮询间隔。

您可以通过将 "pollingInterval": 4000(本例中为 4 秒)添加到您的 nodemon.json 文件或使用 -P--polling-interval 标志来指定它命令。