我想这样做,我可以在下面的代码中运行多个命令:
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
如何执行多个命令?
当前回答
这对我有用:
version: '3.1'
services:
db:
image: postgres
web:
build: .
command:
- /bin/bash
- -c
- |
python manage.py migrate
python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
dockercompose尝试在运行命令之前取消对变量的引用,因此如果您希望bash处理变量,则需要通过加倍它们来逃避美元符号。。。
command:
- /bin/bash
- -c
- |
var=$$(echo 'foo')
echo $$var # prints foo
…否则会出现错误:
服务“web”中“命令”选项的插值格式无效:
其他回答
使用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
这是我解决这个问题的方法:
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
"
使用一个工具,例如等待或码头化。这些是可以包含在应用程序图像中的小型包装脚本。或者编写自己的包装脚本来执行更特定于应用程序的命令。根据:https://docs.docker.com/compose/startup-order/
这个线程中已经有很多很好的答案,然而,我发现其中的一些组合似乎最有效,尤其是对于基于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中为每个图像使用入口点。