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

如何在启动Django服务器时同步运行Python脚本(Docker环境)

解决Docker中同时启动Django服务与Kafka脚本的问题

Docker的CMD指令只会执行最后一条,要同时运行两个进程,有以下几种可靠方案:

方案1:使用Shell脚本作为入口

创建一个启动脚本(比如start.sh),在脚本中后台启动Django服务,前台运行Kafka消费者脚本,确保容器不会提前退出:

#!/bin/bash
# 后台启动Django服务器
python manage.py runserver 0.0.0.0:8443 &
# 前台运行Kafka消费者脚本
python ./consumer.py
# 等待所有后台进程,避免容器提前终止
wait

然后修改Dockerfile:

# 复制启动脚本到容器内
COPY start.sh ./
# 给脚本添加执行权限
RUN chmod +x start.sh
# 执行启动脚本
CMD ["./start.sh"]

方案2:使用进程管理工具(推荐复杂场景)

如果需要更稳定的进程监控与管理,可以用supervisord:

  1. 在Dockerfile中安装supervisor:
RUN apt-get update && apt-get install -y supervisor
  1. 创建supervisord.conf配置文件:
[supervisord]
nodaemon=true  # 让supervisor在前台运行,避免容器退出

[program:django-server]
command=python manage.py runserver 0.0.0.0:8443
directory=/app  # 替换为你的项目根目录
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:kafka-consumer]
command=python ./consumer.py
directory=/app  # 替换为你的项目根目录
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
  1. 修改Dockerfile,复制配置并启动supervisord:
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

方案3:临时快速方案(不推荐生产环境)

直接用shell命令组合,将Django服务后台运行,前台执行消费者脚本:

CMD ["sh", "-c", "python manage.py runserver 0.0.0.0:8443 & python ./consumer.py"]

这种方式简单但缺乏进程监控,若后台的Django服务意外退出,容器不会感知并重启它,仅适合测试场景。

内容的提问来源于stack exchange,提问作者Sugunanayak Darbe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:04:50