如何在Docker Compose中实现服务终止后启动另一服务
解决方案:让Benthos在App任务完成后启动
Docker Compose没有原生支持"等待另一个服务终止"的依赖条件,但可以通过两种可靠方式实现你的需求:
方法1:让Benthos等待App容器成功退出
利用Docker CLI命令检查App容器的退出状态,在Benthos启动前添加等待逻辑,适合开发环境快速实现。
修改docker-compose.yml
给Benthos服务添加前置等待命令,检查App容器是否成功退出(退出码为0):
version: '3.8' services: db: image: postgres:14 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 environment: POSTGRES_PASSWORD: postgres app: build: ./app depends_on: db: condition: service_healthy environment: DB_HOST: db DB_USER: postgres DB_PASSWORD: postgres DB_NAME: postgres benthos: image: jeffail/benthos:latest depends_on: db: condition: service_healthy command: > sh -c " # 替换为你的实际App容器名(可通过docker-compose ps查看) until docker inspect --format='{{.State.ExitCode}}' ${COMPOSE_PROJECT_NAME}_app_1 | grep -q '0'; do sleep 2 done benthos -c /config.yaml " volumes: - ./benthos/config.yaml:/config.yaml - /var/run/docker.sock:/var/run/docker.sock # 挂载Docker sock以获取容器状态
方法2:通过共享文件传递任务完成信号
让App在执行完print_data后创建一个标记文件,Benthos等待该文件出现再启动,这种方法无需挂载Docker sock,更适合生产环境。
步骤1:修改Python脚本
在任务完成后创建标记文件:
import psycopg2 import os def print_data(): conn = psycopg2.connect( host="db", database="postgres", user="postgres", password="postgres" ) cur = conn.cursor() cur.execute("SELECT * FROM some_table;") rows = cur.fetchall() for row in rows: print(row) cur.close() conn.close() print("Data printed successfully") if __name__ == "__main__": print_data() # 创建任务完成标记文件 with open("/shared/app_completed", "w") as f: f.write("done")
步骤2:修改docker-compose.yml
添加共享卷,让Benthos等待标记文件:
version: '3.8' services: db: image: postgres:14 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 environment: POSTGRES_PASSWORD: postgres app: build: ./app depends_on: db: condition: service_healthy environment: DB_HOST: db DB_USER: postgres DB_PASSWORD: postgres DB_NAME: postgres volumes: - shared_volume:/shared benthos: image: jeffail/benthos:latest depends_on: db: condition: service_healthy command: > sh -c " until [ -f /shared/app_completed ]; do sleep 2 done benthos -c /config.yaml " volumes: - ./benthos/config.yaml:/config.yaml - shared_volume:/shared volumes: shared_volume:
额外提示
- 方法1需确保Benthos容器能访问Docker daemon,若权限不足可调整容器用户权限;方法2更安全,无daemon访问风险。
- 若App可能执行失败,可给等待逻辑添加超时判断,避免无限等待。
内容的提问来源于stack exchange,提问作者user23733163
相关产品推荐
相关产品推荐

