【问题标题】:Docker Nodemon not reloading on changes even though -L is set即使设置了 -L,Docker Nodemon 也不会重新加载更改
【发布时间】:2022-02-03 02:28:43
【问题描述】:

您好,我正在尝试对我当前正在开发的应用程序进行 dockerize。它使用 nodejs 和 mariadb。我在弄清楚如何使 nodemon 工作时遇到了一些困难。

我尝试使用--legacy-watch 或-L 这是简短的形式,但它并没有改变结果。

NPM 正确安装了所有依赖项,我什至得到了 nodemon 文本,但是当我进行更改时它不会重新启动服务器。

如果有人可以帮忙,我会很高兴

package.json:

{
  "name": "nodejs_mariadb_docker_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/index.js",
    "dev": "nodemon -L src/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.2",
    "mariadb": "^2.5.5",
    "nodemon": "^2.0.15"
  }
}

nodejs 的 Dockerfile:

# Specifies the image of your engine
FROM node:16.13.2

# The working directory inside your container
WORKDIR /app

# Get the package.json first to install dependencies
COPY package.json /app

# This will install those dependencies
RUN npm install

# Copy the rest of the app to the working directory
COPY . /app

# Run the container
CMD ["npm", "run", "dev"]

和 docker compose 文件:

version: "3"
services: 
  node:
    build: .
    container_name: express-api
    ports:
      - "80:8000"
    depends_on: 
      - mysql

  mysql:
    image: mariadb:latest
    ports:
      - "3306:3306"
    environment: 
      MYSQL_ROOT_PASSWORD: "password"
    volumes:
      - mysqldata:/var/lib/mysql
      - ./mysql-dump:/docker-entrypoint-initdb.d
volumes:
    mysqldata: {}

【问题讨论】:

    标签: node.js docker nodemon


    【解决方案1】:

    所以明显的问题是您没有将代码安装到容器中。这就是为什么 nodemon 看不到任何更改并对其做出反应的原因。

    此外,在本地开发应用程序并仅使用 docker 作为打包/运送它的手段可能更直接。

    如果你还想走这条路,我会建议这样。

    services: 
      express-api:
        build: ./
        # overwrite the prod command
        command: npm run dev
        ports:
          - "80:8000"
        volumes:
          # mount your code folder into the app folder
          - .:/app
    
    # mysql stuff ...
    

    在您的 dockerfile 中,您可以将命令交换为生产命令,因为在开发中,compose 会覆盖它。

    FROM node:16.13.2
    WORKDIR /app
    COPY package.json package-lock.json ./
    # use ci to install from the lock file, 
    # to avoid suprises in prod
    RUN npm ci
    COPY . ./
    # use the prod command
    CMD ["npm", "run", "start"]
    

    这会在开发中做一些多余的工作,比如复制代码,但应该没问题。

    此外,例如,您可能希望使用 .dockerignore 来忽略 mysqldump。否则,它会被复制到图像中,这可能是不可取的。

    另请注意,通过npm ci,您的依赖项已被锁定,并且不会自动更新。如果您的锁定文件与 package.json 不同步,它也会抛出错误。这就是你想要的生产。如果您在本地开发,您可以在本地运行 npm install 或通过 docker exec 来增加依赖项(如果需要)。然后您可以检查是否没有任何损坏,并确保您的 prod 映像会很好,因为它再次从锁定文件中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2017-02-26
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 2022-07-19
      • 2019-02-27
      • 2018-02-05
      相关资源
      最近更新 更多