Shell 脚本控制 uWSGI 服务器的启动、停止

现在有一个 Django 应用,通过 Nginx 接受外网请求后使用 uwsgi 协议转发至内网 uWSGI 服务器,uWSGI 服务器再和 Django 应用进行通信。

为了方便管理,我决定写一个 Shell 脚本来控制 uWSGI 服务器的启动和停止。

这样以后项目中如果需要同时启动别的进程,也可以通过简单修改 Shell 脚本来实现对整个项目的一键控制。

首先把 uWSGI 服务器的各项选项参数写入到 ini 文件,并设置守护进程。

然后编写 Shell 脚本如下(dino 为项目简称):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash

usage="Usages: dino [start|stop|restart|status]"

if [ ! -n "$1" ]
then
echo "$usage";
exit 0
fi

process="dino_uwsgi"

run_start_cmd(){
`/usr/bin/uwsgi --ini /home/dennic/dino_uwsgi.ini`
}

is_exist(){
if [ $(ps -ef | grep -c ${process}) -gt 1 ]
then
return 1
else
return 0
fi
}

is_running(){
is_exist
if [ $? == 1 ]
then
echo -e "\033[32mdino uWSGI service is running!\033[0m";
return 1
else
echo -e "\033[33mdino uWSGI service is not running!\033[0m"
return 0
fi
}

kill_all(){
echo -e "shutting down dino uWSGI service ...... \c"
pids=$(ps x | grep ${process} | grep -v grep | awk '{print $1}')
for pid in $pids
do
`kill -9 $pid`
done
sleep 1
is_exist
if [ $? == 0 ]
then
echo -e "\033[32m[OK]\033[0m";
return 1
else
echo -e "\033[31m[Fail]\033[0m"
return 0
fi
}

start_service(){
run_start_cmd
echo -e "Starting dino uWSGI service ...... \c";
sleep 1
is_exist
if [ $? == 1 ]
then
echo -e "\033[32m[OK]\033[0m";
return 1
else
echo -e "\033[31m[Fail]\033[0m"
return 0
fi
}

cmd=$1

# start
if [ $cmd = start ]
then
is_running;
if [ $? == 0 ]
then
start_service
fi

# status
elif [ $cmd = status ];then
is_running

# stop
elif [ $cmd = stop ];then
kill_all

# restart
elif [ $cmd = restart ];then
is_running
if [ $? == 1 ]
then
kill_all
if [ $? == 1 ]
then
start_service
fi
else
start_service
fi

else
echo "$usage";
fi

将 Shell 脚本保存为 dino.sh,并且创建软连接到 /usr/bin/dino

尝试运行脚本:

Shell 脚本控制 uWSGI 服务器的启动、停止

https://blog.dennic365.com/2017/10/21/uwsgi-manage-shell/

作者

Dennic

发布于

2017-10-21

更新于

2024-02-25

许可协议

评论