运行 按服务去应用

Run go app by service

在 CentOS 6.8 中,我有一个 golang 应用程序,运行 在命令 go run main.go 中,我需要创建一个系统服务 运行 它在启动时像服务 httpd.
我知道我必须创建类似 /etc/rc.d/init.d/httpd 的文件,但我不知道如何对 运行 该命令执行此操作。

我假设您尝试使用 apache 网络服务器。实际上,Go web 服务器本身就足够了。主要目的是运行去系统service.So中的web服务器,你可以使用tmuxhttps://tmux.github.io/或者nohup 到 运行 作为系统服务。您也可以使用 apache 或 nginx 网络服务器作为代理。

首先,您需要构建您的 Go 二进制文件并将其放入您的路径中。

go install main.go

如果您的 "main" 文件名为 main,go install 将在您的路径中放置一个名为 "main" 的二进制文件,因此我建议您将文件重命名为您的 project/server.

mv main.go coolserver.go
go install coolserver.go

您可以运行 coolserver 确保一切正常。如果你的 $GOPATH 设置正确,它就会。

这是一个名为 service.sh

的 init.d 服务示例
#!/bin/sh
### BEGIN INIT INFO
# Provides:          <NAME>
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       <DESCRIPTION>
### END INIT INFO

SCRIPT=<COMMAND>
FLAGS="--auth=user:password"
RUNAS=<USERNAME>

PIDFILE=/var/run/<NAME>.pid
LOGFILE=/var/log/<NAME>.log

start() {
  if [ -f /var/run/$PIDNAME ] && kill -0 $(cat /var/run/$PIDNAME); then
    echo 'Service already running' >&2
    return 1
  fi
  echo 'Starting service…' >&2
  local CMD="$SCRIPT  $FLAGS &> \"$LOGFILE\" & echo $!"
  su -c "$CMD" $RUNAS > "$PIDFILE"
  echo 'Service started' >&2
}

stop() {
  if [ ! -f "$PIDFILE" ] || ! kill -0 $(cat "$PIDFILE"); then
    echo 'Service not running' >&2
    return 1
  fi
  echo 'Stopping service…' >&2
  kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE"
  echo 'Service stopped' >&2
}

uninstall() {
  echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "
  local SURE
  read SURE
  if [ "$SURE" = "yes" ]; then
    stop
    rm -f "$PIDFILE"
    echo "Notice: log file is not be removed: '$LOGFILE'" >&2
    update-rc.d -f <NAME> remove
    rm -fv "[=12=]"
  fi
}

case "" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  uninstall)
    uninstall
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "Usage: [=12=] {start|stop|restart|uninstall}"
esac

复制到/etc/init.d:

cp "service.sh" "/etc/init.d/coolserver"
chmod +x /etc/init.d/coolserver

记得替换

<NAME> = coolserver
<DESCRIPTION> = Describe your service here (be concise)
<COMMAND> = /path/to/coolserver
<USER> = Login of the system user the script should be run as 

启动并测试您的服务并将服务安装为 运行 在启动时:

service coolserver start
service coolserver stop
update-rc.d coolserver defaults