You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让执行Git克隆的Docker Compose容器持续运行?

解决容器执行初始化任务后退出的问题

核心原因

你添加的tty: true和stdin_open: true仅适用于交互式容器,而你的场景是一次性初始化任务(Git克隆+文件移动)执行完成后,未启动维持容器运行的主进程——容器的生命周期完全依赖主进程,主进程结束容器就会退出,问题出在你的启动命令只执行了初始化操作,没启动Nginx的前台进程。

具体解决方案

方案1:用自定义脚本串联任务与Nginx启动

编写一个脚本,先完成初始化操作,再启动Nginx前台进程,将这个脚本作为容器的启动命令:

  1. 在项目目录下创建start.sh脚本:
#!/bin/sh
# 克隆目标仓库(替换为你的仓库地址)
git clone --depth 1 https://your-repo-url.git /tmp/repo || true
# 将仓库文件移动到Nginx HTML目录(路径根据镜像实际情况调整)
mv /tmp/repo/* /usr/share/nginx/html/
# 启动Nginx前台进程(确保容器持续运行)
nginx -g 'daemon off;'
  1. 给脚本添加执行权限:
chmod +x start.sh
  1. 修改Docker Compose配置,挂载脚本并指定启动命令:
services:
  nginx:
    image: emarcs/nginx-git
    volumes:
      - ./start.sh:/start.sh
    command: /start.sh
    ports:
      - "80:80"
    # 保留你需要的其他配置

方案2:直接在启动命令中串联操作

如果不想单独写脚本,可直接在Docker Compose的command字段用命令串联,确保初始化完成后启动Nginx:

services:
  nginx:
    image: emarcs/nginx-git
    command: >
      sh -c "git clone --depth 1 https://your-repo-url.git /tmp/repo || true &&
             mv /tmp/repo/* /usr/share/nginx/html/ &&
             nginx -g 'daemon off;'"
    ports:
      - "80:80"

关键注意事项

  • 必须用nginx -g 'daemon off;'启动Nginx:Nginx默认后台运行,会导致容器主进程退出,daemon off;强制其前台运行,才能维持容器生命周期。
  • 添加|| true是为了避免仓库已克隆时,git clone报错中断后续命令执行。
  • 你的场景不需要tty: true和stdin_open: true,可直接移除这两个配置。

内容的提问来源于stack exchange,提问作者Raja Muneer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:50:51