通常,Docker容器适合运行单个进程,但是很多时候我们需要在Docker容器中运行多个进程。这时有两种不同方法来运行多进程容器:使用shell脚本或者supervisor,两种方法都很简单,各有优劣,只是有一些值得注意的细节。这里只讲用脚本的处理方法。
写一个脚本multiple_thread.sh,脚本功能运行两个python程序,将运行结果保存到log文件中。脚本内容如下
#!/bin/bash
# Start the first process
nohup python -u /tmp/ > /tmp/ 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/ > /tmp/ 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 /tmp/
COPY /tmp/
COPY multiple_thread.sh /tmp/multiple_thread.sh
CMD bash /tmp/multiple_thread.sh