Docker中运行多个进程时的处理

通常,Docker容器适合运行单个进程,但是很多时候我们需要在Docker容器中运行多个进程。这时有两种不同方法来运行多进程容器:使用shell脚本或者supervisor,两种方法都很简单,各有优劣,只是有一些值得注意的细节。这里只讲用脚本的处理方法。

写一个脚本multiple_thread.sh,脚本功能运行两个python程序,将运行结果保存到log文件中。脚本内容如下

#!/bin/bash
# Start the first process
nohup python -u /tmp/thread1.py > /tmp/thread1.log 2>&1 &
ps aux |grep thread1 |grep -q -v grep
PROCESS_1_STATUS=$?
echo "thread1 status..."
echo $PROCESS_1_STATUS
if [ $PROCESS_1_STATUS -ne 0 ]; then
echo "Failed to start my_first_process: $PROCESS_2_STATUS"
exit $PROCESS_1_STATUS
fi
sleep 5
# Start the second process
nohup python -u /tmp/thread2.py > /tmp/thread2.log 2>&1 &
ps aux |grep thread2 |grep -q -v grep
PROCESS_2_STATUS=$?
echo "thread2 status..."
echo $PROCESS_2_STATUS
if [ $PROCESS_2_STATUS -ne 0 ]; then
echo "Failed to start my_second_process: $PROCESS_2_STATUS"
exit $PROCESS_2_STATUS
fi
# 每隔60秒检查进程是否运行
while sleep 60; do
ps aux |grep thread1 |grep -q -v grep
PROCESS_1_STATUS=$?
ps aux |grep thread2 |grep -q -v grep
PROCESS_2_STATUS=$?
# If the greps above find anything, they exit with 0 status
# If they are not both 0, then something is wrong
if [ $PROCESS_1_STATUS -ne 0 -o $PROCESS_2_STATUS -ne 0 ]; then
echo "One of the processes has already exited."
exit 1
fi

下一步制作Dockerfile:       

FROM centos:latest

COPY thread1.py /tmp/thread1.py
COPY thread2.py /tmp/thread2.py
COPY multiple_thread.sh /tmp/multiple_thread.sh

CMD bash /tmp/multiple_thread.sh



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值