docker-compose always exec using nodejs

docker-compose always exec using nodejs

我在这件事上抓狂了。我不知道哪里出了问题,但 docker 容器似乎总是执行我用 nodejs 发出的任何命令。它不会导致错误的唯一方法是当我将“index.js”作为单个命令放在 docker-compose.yml

我是 docker 的新手,但是有什么地方我应该看看吗?

我的docker文件:

FROM node:17
WORKDIR /opt/application
COPY ./certificate/server* ./certificate/
COPY package.json .
COPY config.json .
COPY tsconfig.json .
COPY ./src/ ./src
RUN npm install nodemon typescript -g
RUN npm install
RUN tsc -p .

docker-compose.yml

version: "3.9"
services:
  web:
    build: .
    ports: 
      - "80:3000"
    container_name: nodejs
    volumes:
      - "./src:/opt/application/src"
    depends_on:
      - "mongo"
    command:
      - "tsc -w"
      - "nodemon"
  mongo:
    image: "mongo:latest"
    ports:
      - "27017:27017"
      

不知道添加nodejs的配置在哪里

感谢任何帮助。谢谢

假定您完全清楚您已在容器中将工作目录设置为/opt/application。尝试:

version: "3.9"
services:
  web:
    build: .
    ports: 
      - "80:3000"
    container_name: nodejs
    volumes:
      - "./src:/opt/application/src"
    depends_on:
      - "mongo"
    command: ["tsc","-w","nodemon"]
  mongo:
    image: "mongo:latest"
    ports:
      - "27017:27017"

嗯,当然是 运行 每个带有 node 的命令,它明确表示该图像的作用。

当我们执行docker history node:17 --no-trunc时,我们可以看到基础图像的最后两层是:

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["node"]

如果我们得到docker-entrypoint.sh的内容,我们可以看到下面的脚本:

#!/bin/sh
set -e

# Run command with node if the first argument contains a "-" or is not a system command. The last
# part inside the "{}" is a workaround for the following bug in ash/dash:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=874264
if [ "${1#-}" != "" ] || [ -z "$(command -v "")" ] || { [ -f "" ] && ! [ -x "" ]; }; then
  set -- node "$@"
fi

exec "$@"

因此,由于您使用 tsc -w 作为第一个命令,它会识别破折号并且命令以 node 运行(如预期)。

此外,您似乎误解了 Compose 文件中 command 的功能:you cannot add more than one command.

所以基本上你要强制执行的是以下内容:

CMD ["tsc -w", "nodemon"]

我想您要实现的目标如下:

package.json

"start": "tsc && concurrently \"tsc -w\" \"nodemon\" "

docker-compose.yml

 version: "3.9"
services:
  web:
    build: .
    ports: 
      - "80:3000"
    container_name: nodejs
    volumes:
      - "./src:/opt/application/src"
    depends_on:
      - "mongo"
    command: npm run start
  mongo:
    image: "mongo:latest"
    ports:
      - "27017:27017"