WhatAKitty Daily

A Programmer's Daily Record

封装Ngrok服务

WhatAKitty   阅读次数loading...

背景

在公司部署集成环境的时候,由于是内网环境,但是有时候常常需要在外网使用JIRA、GITLAB等等这些服务。查询了一下资料,采用了NGROK这款开源软件,用于将内网服务暴露到外网中。不过,因为ngrok的服务端和客户端只是简单的一个程序,对于习惯于直接进行服务管理的我来说不太方便。所以,在这片文章内,会介绍如何将NGROK封装为一个服务。

SHELL脚本

话不多说,直接上代码:

Service

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
#!/bin/bash
#
# chkconfig: 345 70 30
# description: ngrokd service
# processname: ngrokd

# Source function library.
. /etc/init.d/functions

RETVAL=0
prog="ngrokd"
LOCKFILE=/var/lock/subsys/$prog

# Declare variables for Ngrokd Server
NGROKD_PATH=/path/to/ngrok
NGROKD_BIN=$NGROKD_PATH/bin

# 这里没有将domain.com采用参数形式暴露,因为时间紧张,等以后研究后再加上。
start() {
[ -x $exec ] || exit 5
echo -n "Starting $prog: "
# use daemon to start the service
daemon $exec $NGROKD_BIN/ngrokd -tlsKey=$NGROKD_PATH/server.key -tlsCrt=$NGROKD_PATH/server.crt -domain="domain.com" -httpAddr="" -httpsAddr="" -log="/root/ngrok/ngrok/logs/ngrok.log" &
retval=$?
echo
return $retval
}

stop() {
echo -n "Stoping $prog: "
killproc $prog -TERM
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}

restart() {
stop
start
}

rh_status() {
# run checks to determine if the service is running or use generic status
status $prog
}

rh_status_q() {
rh_status >/dev/null 2>&1
}

case "$1" in
start)
#Only if not running, start
rh_status_q && echo "process already started" && exit 0
$1
;;
stop)
stop
;;
restart)
restart
;;
status)
rh_status
;;
*)
echo "Usage: $prog {start|stop\}"
exit 1
;;
esac
exit $RETVAL

Systemd

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=ngrok client
After=network.target

[Service]
Type=simple
ExecStart=/path/to/ngrokd/bin/ngrokd -tlsKey=/path/to/ngrokd/server.key -tlsCrt=/path/to/ngrokd/server.crt -domain="domain.com" -httpAddr="" -httpsAddr="" -log="/path/to/ngrokd/logs/ngrok.log"
ExecStop=ps aux|grep ngrokd|awk '{print $2}'|xargs kill -9
Restart=on-failure
KillSignal=SIGCONT

[Install]
WantedBy=multi-user.target