Nodemon 在 Docker 上使用来自 package.json 的 npm 脚本无法正常工作

Nodemon not working using npm script from package.json on Docker

我正在 Docker 上使用 NodeJS 和 Nodemon。当我尝试直接在 docker 撰写文件中使用 nodemon 命令 运行 我的 NodeJS 应用程序时,它 运行s.

像这样(工作):[docker-compose]

command: nodemon source/index.js

但是当我使用来自 package.json 的脚本时,它不起作用

像这样(不工作):[docker-compose]

command: npm run dev

我的 package.json 文件在哪里

"scripts": {
    "start": "node source/index.js",
    "dev": "nodemon source/index.js"
  }

我尝试了不同的方法,当我只是 运行 启动没有 nodemon 的脚本时,它有效

像这样(工作):[docker-compose]

command: npm run start

但是当我尝试再次使用 dev 并在其中使用 nodemon 命令时,它不起作用。容器不会启动。我也尝试了以下方法,它也有效

像这样(工作):[docker-compose]

command: nodemon --exec npm start

我还是不明白,为什么 nodemon 命令在脚本中不起作用 dev

我在 Swarm 模式下使用 Docker

这是我的两个文件

docker-撰写

version: '3.7'

services:

    node-service:

        image: node-img:1.0

        ports:
        - 4000:4000

        working_dir: "/node-dir"

        volumes:
        - ./node-dir/source:/node-dir/source

        networks:
            - ness-net

        command: npm run dev

networks:

    ness-net:

package.json

{
  "name": "node-pkg",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node source/index.js",
    "dev": "nodemon source/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

在运行nodemon时需要添加一个环境变量指向npm C:\........\npm路径应该是这样的,然后选择一个名字

试试这个解决方案:

services:
 node-app:
  container_name: node-app
  image: node:latest
  restart: always
  volumes:
    - ./node/source:home/node/source
  working_dir: /home/node/source
  ports:
   - 4000:4000
  networks:
   - main-network
  command: "tail -f /dev/null && npm start"
  depends_on:
   - db
  logging:
    driver: "json-file"
    options:
     max-file: "4"
     max-size: "100m

这里是package.json

"main": "index.js",
"scripts": {
  "preinstall": "npm i nodemon -g",
  "start": "nodemon index.js",
}

请确保工作目录中应该有 index.js 和 package.json。

只需添加“.”像这样 package.json 中定义路径

"scripts": {
    "start": "node ./source/index.js",
    "dev": "nodemon ./source/index.js"
  }