等待脚本覆盖默认 CMD 并退出 Docker 容器

Wait script overrides default CMD and exits Docker container

Docker-compose.yaml:

version: "3"
services:
  mysql:
    image: mysql:5.7
    environment:
      MYSQL_HOST: localhost
      MYSQL_DATABASE: mydb
      MYSQL_USER: mysql
      MYSQL_PASSWORD: 1234
      MYSQL_ROOT_PASSWORD: root
    ports:
      - "3307:3306"
    expose:
      - 3307
    volumes:
      - /var/lib/mysql
      - ./mysql/migrations:/docker-entrypoint-initdb.d
    restart: unless-stopped
  web:
    build:
      context: .
      dockerfile: web/Dockerfile
    volumes:
      - ./:/web
    ports:
      - "32768:3000"
    environment:
      NODE_ENV: development
      PORT: 3000
    links:
      - mysql:mysql
    depends_on:
      - mysql
    expose:
      - 3000
    command: ["./wait-for-it.sh", "mysql:3306", "--", "npm start"]

网络Docker文件:

FROM node:6.11.2-slim

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

COPY . /usr/src/app

CMD [ "npm", "start" ] # So this is overridden by the wait script and doesn't execute

我正在使用这个等待脚本: https://github.com/vishnubob/wait-for-it

等待脚本工作正常,但它会覆盖 Web 容器的现有启动命令: CMD [ "npm", "start" ]

正如您在 docker-compose 文件中看到的,我使用这种方法启动 npm start:
command: ["./wait-for-it.sh", "mysql:3306", "--", "npm start"]

我尝试了一些替代方法,例如:
command: ["./wait-for-it.sh", "mysql:3306", "--", "CMD ['npm', 'start'"]
command: ["./wait-for-it.sh", "mysql:3306", "--", "docker-entrypoint.sh"]

只是它不起作用。我从网络容器中得到这个错误: web_1 | ./wait-for-it.sh: line 174: exec: npm start: not found

这是怎么回事?

所以首先,如果您在 docker-compose 中使用 command,那么它将覆盖 CMD,这是预期的行为。 docker怎么知道你想同时执行它们。

接下来你的方法有点错误,CMD

command: ["./wait-for-it.sh", "mysql:3306", "--", "npm start"]

翻译成你在执行

./wait-for-it.sh mysql:3306 -- "npm start"

应该会失败,因为没有命令 npm start 它是 npm 以 start 作为参数。所以将命令更改为

command: ["./wait-for-it.sh", "mysql:3306", "--", "npm", "start"]

command: ./wait-for-it.sh mysql:3306" -- npm start

任何你喜欢的格式