跳到主要内容

docker-compose tips

docker-compose额外增加命令行

不过还没去测试

https://stackoverflow.com/questions/71786923/docker-compose-how-to-run-bash-commands-after-container-has-started-without-ov

you have three main ways to run a command after the container starts:

  • with docker exec -d someContainer some command from the command line,
  • with CMD ["some", "command"] from your Dockerfile
  • with command: some command from a docker-compose file

Docker Compose - How to execute multiple commands?

https://stackoverflow.com/questions/30063907/docker-compose-how-to-execute-multiple-commands

I recommend using sh as opposed to bash because it is more readily available on most Unix based images (alpine, etc).

Here is an example 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"
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

docker-compose, run a script after container has started?

启动一个额外的临时镜像, 只用来运行命令, 初始化第一个镜像.

https://stackoverflow.com/questions/47615751/docker-compose-run-a-script-after-container-has-started

This is the way I use for calling a script after a container is started without overriding the entrypoint.

In my example, I used it for initializing the replicaset of my local MongoDB


services:
mongo:
image: mongo:4.2.8
hostname: mongo
container_name: mongodb
entrypoint: ["/usr/bin/mongod","--bind_ip_all","--replSet","rs0"]
ports:
- 27017:27017
mongosetup:
image: mongo:4.2.8
depends_on:
- mongo
restart: "no"
entrypoint: [ "bash", "-c", "sleep 10 && mongo --host mongo:27017 --eval 'rs.initiate()'"]

In the first part, I simply launch my service (mongo) The second service use a "bash" entry point AND a restart: no <= important I also use a depends_on between service and setup service for manage the launch order.