如何在Docker容器中运行Apache2与Supervisor多服务?
解决方案:让Supervisor同时管理Apache、Cron和Yii队列进程
问题根源:当你用CMD ["/usr/bin/supervisord", ...]替换基础镜像默认的Apache启动命令后,容器仅会启动Supervisor,但Apache未被配置到Supervisor的管理列表中,因此不会自动启动。原Dockerfile中的service apache2 restart仅在镜像构建阶段执行一次,容器启动时不会重复触发。
步骤1:创建Supervisor配置文件
在项目目录下新建supervisord.conf文件,内容如下:
[supervisord] nodaemon=true user=root [program:apache2] command=/usr/sbin/apache2ctl -D FOREGROUND autostart=true autorestart=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 [program:cron] command=cron -f autostart=true autorestart=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 [program:yii-queue-worker] command=php /var/www/html/yii queue/listen --verbose=1 process_name=%(program_name)s_%(process_num)02d numprocs=4 autostart=true autorestart=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0
核心说明:
nodaemon=true:强制Supervisor以前台模式运行(Docker容器需要主进程保持前台状态)apache2使用apache2ctl -D FOREGROUND:确保Apache以前台模式启动,被Supervisor持续监控cron -f:让Cron以前台模式运行,避免进程后台化后被Supervisor判定为退出yii-queue-worker配置4个进程实例,与你原日志中的进程数量匹配
步骤2:修改Dockerfile
在Dockerfile中添加COPY指令,将上述配置文件复制到容器的Supervisor配置目录,同时移除无效的service apache2 restart命令(构建阶段的重启操作对容器启动后的状态无影响):
修改后的关键片段如下:
FROM --platform=linux/amd64 php:8.1.5-apache-buster as development # ... 依赖安装、PHP扩展安装等原有步骤保持不变 ... # 启用rewrite模块(移除service apache2 restart) RUN a2enmod rewrite # ... 别名设置、定时任务配置等原有步骤保持不变 ... # 复制Supervisor配置文件到容器 COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf # 启动Supervisor CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
验证效果
构建并运行容器后,Supervisor会自动启动Apache、Cron和4个Yii队列worker。你可以通过以下命令查看所有进程状态:
docker exec <容器ID> supervisorctl status
正常输出示例:
apache2 RUNNING pid 123, uptime 0:10:32 cron RUNNING pid 124, uptime 0:10:32 yii-queue-worker_00 RUNNING pid 125, uptime 0:10:32 yii-queue-worker_01 RUNNING pid 126, uptime 0:10:32 yii-queue-worker_02 RUNNING pid 127, uptime 0:10:32 yii-queue-worker_03 RUNNING pid 128, uptime 0:10:32
此时网站可正常访问,队列任务和定时任务也能正常运行。
内容的提问来源于stack exchange,提问作者Fadly Dzil
相关产品推荐
相关产品推荐

