设置docker-compose卷

问题描述

我不知道我的docker-compose出了什么问题,我正在尝试实现体积以在使用nodemon在主机上对其进行处理时不断更新容器内的应用程序,但是它不起作用。我几乎整天都在与它作斗争,但是我看不出有什么问题。

FROM node:12.18.4
workdir /usr/src/youtube-clone-app
copY ./ ./
RUN npm install
CMD [ "npm","start" ]
version: "3.8"
services:
    youtube-clone-app:
        build: ./
        container_name: server
        ports:
            - "5000:5000"
        volumes:
            - ./:/usr/src/youtube-clone-app

解决方法

要确切地了解您的需求有些困难,但是请尝试以下方法:

FROM node:12.18.4
WORKDIR /usr/src/youtube-clone-app
RUN npm install
COPY ./ ./
CMD ["nodemon","start"]

请注意CMD ["nodemon","start"],而不是CMD ["npm","start"]。如有必要,请尝试将start替换为您的节点应用脚本,例如./server.js。确保nodemon中有package.json。另外,将上下文添加到您的docker-compose构建选项中。

,

我尝试从您的问题中尽可能多地重新创建您的设置,并且它可以正常工作。问题可能出在卷上或您如何运行nodemon。

您可以尝试像这样调试问题:

  1. CMD [ "npm","start" ]删除Dockerfile
  2. 在Docker Compose中向tty: true服务中添加youtube-clone-app(如下面的示例所示)
  3. 使用Docker Compose docker-compose up --build --force-recreate运行容器(选项--build --force-recreate重建映像)。
  4. 使用bash在容器中运行docker-compose exec youtube-clone-app bash
  5. 在bash中,用ls列出文件,以查看是否所有必需的文件都在那里。
  6. 打印要用cat <file>尝试更新的文件的内容,在主机上更新文件,然后再次打印以查看内容是否已更新。
  7. 使用nodemon index.js(或其他一些作为入口点的文件)在bash中手动运行nodemon

如果在第5步中缺少文件,或者在第6步中未更新文件的内容,则可能是卷装入的问题。

在第7步中,您可以测试哪个命令有效-可能是CMD [ "npm","start" ]是问题所在。

这是我有效的测试设置:

// index.js
console.log("Hello")
# docker-compose.yaml
version: "3.8"

services:
    youtube-clone-app:
        build: ./
        container_name: server
        volumes:
            - ./:/usr/src/youtube-clone-app
        tty: true # Keep container running even if there is no CMD/ENTRYPOINT
# Dockerfile
FROM node:12.18.4
WORKDIR /usr/src/youtube-clone-app
COPY ./ ./
RUN npm install
ENTRYPOINT ["npx","nodemon","index.js"] # If nodemon is installed globally,remove the "npx" argument

如果使用docker-compose up --build --force-recreate运行此测试设置,则应该在终端上看到Hello印刷。更改index.js并保存后,它应该打印更改的内容。

此外,更喜欢ENTRYPOINT胜过CMD。有关更多信息,请查看关于堆栈溢出的What is the difference between CMD and ENTRYPOINT in a Dockerfile?问题。