通过服务运行 go app

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

青春有我
浏览 157回答 2
2回答

繁华开满天机

首先,您需要构建您的 Go 二进制文件并将其放入您的路径中。go install main.go如果您的“主”文件名为 main,go install则会在您的路径中放置一个名为“main”的二进制文件,因此我建议您将文件重命名为您的项目/服务器。mv main.go coolserver.gogo install coolserver.go您可以运行coolserver以确保一切正常。如果你的 $GOPATH 设置正确,它就会出现。这是一个名为的 init.d 服务示例service.sh#!/bin/sh### BEGIN INIT INFO# Provides:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NAME># Required-Start:&nbsp; &nbsp; $local_fs $network $named $time $syslog# Required-Stop:&nbsp; &nbsp; &nbsp;$local_fs $network $named $time $syslog# Default-Start:&nbsp; &nbsp; &nbsp;2 3 4 5# Default-Stop:&nbsp; &nbsp; &nbsp; 0 1 6# Description:&nbsp; &nbsp; &nbsp; &nbsp;<DESCRIPTION>### END INIT INFOSCRIPT=<COMMAND>FLAGS="--auth=user:password"RUNAS=<USERNAME>PIDFILE=/var/run/<NAME>.pidLOGFILE=/var/log/<NAME>.logstart() {&nbsp; if [ -f /var/run/$PIDNAME ] && kill -0 $(cat /var/run/$PIDNAME); then&nbsp; &nbsp; echo 'Service already running' >&2&nbsp; &nbsp; return 1&nbsp; fi&nbsp; echo 'Starting service…' >&2&nbsp; local CMD="$SCRIPT&nbsp; $FLAGS &> \"$LOGFILE\" & echo \$!"&nbsp; su -c "$CMD" $RUNAS > "$PIDFILE"&nbsp; echo 'Service started' >&2}stop() {&nbsp; if [ ! -f "$PIDFILE" ] || ! kill -0 $(cat "$PIDFILE"); then&nbsp; &nbsp; echo 'Service not running' >&2&nbsp; &nbsp; return 1&nbsp; fi&nbsp; echo 'Stopping service…' >&2&nbsp; kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE"&nbsp; echo 'Service stopped' >&2}uninstall() {&nbsp; echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "&nbsp; local SURE&nbsp; read SURE&nbsp; if [ "$SURE" = "yes" ]; then&nbsp; &nbsp; stop&nbsp; &nbsp; rm -f "$PIDFILE"&nbsp; &nbsp; echo "Notice: log file is not be removed: '$LOGFILE'" >&2&nbsp; &nbsp; update-rc.d -f <NAME> remove&nbsp; &nbsp; rm -fv "$0"&nbsp; fi}case "$1" in&nbsp; start)&nbsp; &nbsp; start&nbsp; &nbsp; ;;&nbsp; stop)&nbsp; &nbsp; stop&nbsp; &nbsp; ;;&nbsp; uninstall)&nbsp; &nbsp; uninstall&nbsp; &nbsp; ;;&nbsp; restart)&nbsp; &nbsp; stop&nbsp; &nbsp; start&nbsp; &nbsp; ;;&nbsp; *)&nbsp; &nbsp; echo "Usage: $0 {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&nbsp;启动并测试您的服务并安装要在启动时运行的服务:service coolserver startservice coolserver stopupdate-rc.d coolserver defaults

HUWWW

我假设您尝试使用 apache Web 服务器。实际上,Go Web 服务器本身就足够了。主要目的是在系统服务中运行 Go Web 服务器。因此,您可以使用tmux&nbsp;https://tmux.github.io/或nohup作为系统服务运行。您还可以使用 apache 或 nginx Web 服务器作为代理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go