我想这样做,我可以在下面的代码中运行多个命令:
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
如何执行多个命令?
我想这样做,我可以在下面的代码中运行多个命令:
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
如何执行多个命令?
当前回答
这个线程中已经有很多很好的答案,然而,我发现其中的一些组合似乎最有效,尤其是对于基于Debian的用户。
services:
db:
. . .
web:
. . .
depends_on:
- "db"
command: >
bash -c "./wait-for-it.sh db:5432 -- python manage.py makemigrations
&& python manage.py migrate
&& python manage.py runserver 0.0.0.0:8000"
先决条件:将wait-for-it.sh添加到项目目录中。
来自文档的警告:“(当在生产环境中使用wait for it.sh时),您的数据库可能随时不可用或移动主机……(此解决方案适用于不需要这种弹性的人)。”
编辑:
这是一个很酷的短期解决方案,但对于长期解决方案,您应该尝试在Dockerfile中为每个图像使用入口点。
其他回答
这是我解决这个问题的方法:
services:
mongo1:
container_name: mongo1
image: mongo:4.4.4
restart: always
# OPTION 01:
# command: >
# bash -c "chmod +x /scripts/rs-init.sh
# && sh /scripts/rs-init.sh"
# OPTION 02:
entrypoint: [ "bash", "-c", "chmod +x /scripts/rs-init.sh && sh /scripts/rs-init.sh"]
ports:
- "9042:9042"
networks:
- mongo-cluster
volumes:
- ~/mongors/data1:/data/db
- ./rs-init.sh:/scripts/rs-init.sh
- api_vol:/data/db
environment:
*env-vars
depends_on:
- mongo2
- mongo3
想好了,使用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
另一个想法:
如果像本例一样,构建容器,只需在其中放置一个启动脚本,然后使用命令运行它。或者将启动脚本装载为卷。
基于@Bjorn答案,docker最近引入了特殊的依赖规则,允许您等待“init容器”成功退出
db:
image: postgres
web:
image: app
command: python manage.py runserver 0.0.0.0:8000
depends_on:
db:
migration:
condition: service_completed_successfully
migration:
build: .
image: app
command: python manage.py migrate
depends_on:
- db
我不确定你是否还需要buildkit,但在我这边,它可以与
DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker-compose up