首页 > 解决方案 > Node watch on a docker-compose volume does not register delete events

问题描述

I have a simple Node.js HTTP server running inside a docker container. One of the basic structural folders uses volume from docker-compose.yml to mirror the host and container directory.

Within the Node server, I have a watcher set up to track changes within the volumed directory, using the NPM package chokidar (although I have tried multiple other watchers already with the same result).

const watcher = require("chokidar");

watcher
.watch("./app/experiments", { depth: 0, ignoreInitial: true })
.on("all", (event, path) => {
    console.log(event);
    // ... DO SOME EXPRESS AND WEBPACK STUFF 
});

When I run the Node server locally, the watcher correctly picks up changes to the watched directory. In this case, chokidar is reporting these as addDir or unlinkDir, which correspond to a scaffolding script I run to add or remove new folders into the directory (which is served later via express.static()).

STDOUT:

> addDir
> EXPERIMENT ADDED!
> ...
> unlinkDir
> EXPERIMENT DELETED!

However, when I port the application into a docker container, the behavior changes in a really strange way. I continue to get addDir events when I create new folders in the volumed directory, but I no longer receive unlinkDir (delete) events!. Note that this only happens if I add / delete a file within the volumed directory on the host machine. If I add / delete a file within that directory inside the docker container, my watcher correctly reports all of these events.

In either case, the volumed directory correctly mirrors itself. E.G. the files are actually deleted or added, and I can verify their existence on the host and by shelling into the docker container and running ls.

Any docker geniuses out there with sage wisdom on why this is happening?

KEY STUFF:

OS X 10.13.6

Docker Toolbox:

Dockerfile:

FROM node:8.12.0

WORKDIR /usr/dd-labs

COPY package*.json ./
RUN npm install

COPY app/ ./app
COPY server.js ./
COPY webpack/ ./webpack

EXPOSE 8080

Docker-compose.yml:

version: "2"
services:
  app:
    image: #someImageName
    build: .
    ports:
      - "8080:8080"
    labels:
      io.rancher.container.pull_image: always
    environment:
      VIRTUAL_HOST: labs.docker
    volumes:
      - ./app:/usr/dd-labs/app
    command: [sh, -c, "npm run start:dev"]

标签: node.jsdockerdocker-composewatchchokidar

解决方案


您可能正在使用 Docker for Windows,众所周知,它不支持从主机到容器的文件系统事件传播。

一种解决方法是在开发环境中使用轮询。使用 chokidar,您需要usePolling: true选择。


推荐阅读