本文翻译自:Using Docker-Compose, how to execute multiple commands
I want to do something like this where I can run multiple commands in order. 我想做这样的事情,我可以按顺序运行多个命令。
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
#1楼
参考:https://stackoom.com/question/228zj/使用Docker-Compose-如何执行多个命令
#2楼
Figured it out, use bash -c
. 想出来,使用bash -c
。
Example: 例:
command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
Same example in multilines: 多行中的相同示例:
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
"
#3楼
Another idea: 另一个想法:
If, as in this case, you build the container just place a startup script in it and run this with command. 如果,就像在这种情况下,您构建容器只需在其中放置一个启动脚本并使用命令运行它。 Or mount the startup script as volume. 或者将启动脚本作为卷安装。
#4楼
I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type): 我在一个单独的短暂容器中运行像启动之类的预启动之类的东西(注意,compose文件必须是版本'2'类型):
db:
image: postgres
web:
image: app
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
depends_on:
- migration
migration:
build: .
image: app
command: python manage.py migrate
volumes:
- .:/code
links:
- db
depends_on:
- db
This helps things keeping clean and separate. 这有助于保持清洁和分离。 Two things to consider: 需要考虑的两件事:
You have to ensure the correct startup sequence (using depends_on) 您必须确保正确的启动顺序(使用depends_on)
you want to avoid multiple builds which is achieved by tagging it the first time round using build and image; 你想避免多次构建,这是通过使用构建和图像第一次标记它来实现的; you can refer to image in other containers then 你可以参考其他容器中的图像
#5楼
If you need to run more than one daemon process, there's a suggestion in the Docker documentation to use Supervisord in an un-detached mode so all the sub-daemons will output to the stdout. 如果您需要运行多个守护程序进程, Docker文档中的建议是在未分离模式下使用Supervisord ,以便所有子守护进程都将输出到stdout。
From another SO question, I discovered you can redirect the child processes output to the stdout. 从另一个SO问题,我发现你可以将子进程输出重定向到stdout。 That way you can see all the output! 这样你就可以看到所有输出!
#6楼
Use a tool such as wait-for-it or dockerize . 使用wait-for-it或dockerize等工具。 These are small wrapper scripts which you can include in your application's image. 这些是小包装脚本,您可以将其包含在应用程序的图像中。 Or write your own wrapper script to perform a more application-specific commands. 或编写自己的包装器脚本以执行更多特定于应用程序的命令。 according to: https://docs.docker.com/compose/startup-order/ 根据: https : //docs.docker.com/compose/startup-order/