我想这样做,我可以在下面的代码中运行多个命令:

db:
  image: postgres
web:
  build: .
  command: python manage.py migrate
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db

如何执行多个命令?


当前回答

如果其他人试图使用基于Windows的容器计算多个命令,则以下格式有效:命令:“cmd.exe/c调用c:\Temp/script1.bat&&dir&&c:/Temp/script2.bat&&…”

包括“呼叫”指令是我修复它的原因。

或者,如果每个命令都可以在没有前面命令的情况下执行,则只需用分号分隔每个命令:命令:“cmd.exe/c调用c:\Temp/script1.bat;dir;c:\Temp/sscript2.bat;…”

其他回答

我建议使用sh而不是bash,因为它在大多数基于Unix的映像(alpine等)上更容易使用。

下面是docker-compose.yml示例:

version: '3'

services:
  app:
    build:
      context: .
    command: >
      sh -c "python manage.py wait_for_db &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"

这将按顺序调用以下命令:

python manage.py wait_for_db-等待数据库准备就绪python manage.py migrate-运行任何迁移python manage.py runserver 0.0.0.0:8000-启动我的开发服务器

使用bash-c在docker compose文件中运行多个命令。

command: >
    bash -c "python manage.py makemigrations
    && python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000"

资料来源:https://intellipaat.com/community/19590/docker-run-multiple-commands-using-docker-compose-at-once?show=19597#a19597

想好了,使用bash-c。

例子:

command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"

多行中的相同示例:

command: >
    bash -c "python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000"

Or:

command: bash -c "
    python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000
  "

最干净?

---
version: "2"
services:
  test:
    image: alpine
    entrypoint: ["/bin/sh","-c"]
    command:
    - |
       echo a
       echo b
       echo c

另一个想法:

如果像本例一样,构建容器,只需在其中放置一个启动脚本,然后使用命令运行它。或者将启动脚本装载为卷。