ExecStart 在 Golang webapp 的 systemd 服务中失败

ExecStart fails in systemd service for Golang webapp

我是 golang 的新手,正在尝试在我的服务器上托管一个简单的网站。

我在 Ubuntu 18.04

我的域名根目录在/var/www/vhosts/mydomain.com/mydomain.com

我有一个 main.go 文件,它在浏览器中呈现一个简单的 Hello World。

当我从这个目录 go run main.go 时,网页工作正常。

现在我正在尝试创建一项服务,以便在我关闭 shell 时保持网页可用。

为此,我在 /etc/systemd/system 创建了一个名为 golangweb.service 的新 service

该文件的内容是:

[Unit]
Description = Go Server

[Service]
ExecStart=/var/www/vhosts/mydomain.com/mydomain.com
Type=simple
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

保存文件后,我按顺序插入以下命令:

sudo systemctl daemon-reload
sudo systemctl enable golangweb.service
sudo systemctl start golangweb.service
sudo systemctl status golangweb.service

当我尝试获取状态时出现以下错误(我修正了那里的一些数据):

 golangweb.service - Go Server
   Loaded: loaded (/etc/systemd/system/golangweb.service; enabled; vendor preset: enabl
   Active: activating (auto-restart) (Result: exit-code) since Fri xx-xx-xx 23:43:52
  **Process: xx ExecStart=/var/www/vhosts/mydomain.com/mydomain.com (code=exited, sta
 Main PID: xx (code=exited, status=203/EXEC)**

Mai xx xx:xx:xx xxxxx.xxxx.xxxx.systemd[1]: golangweb.service: Failed with re
Warning: Journal has been rotated since unit was started. Log output is incomplete or u
lines 1-8/8 (END)
● golangweb.service - Go Server
   Loaded: loaded (/etc/systemd/system/golangweb.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Fri xx-xx-xx xx:xx:xx CEST; 3s ago
  Process: xx ExecStart=/var/www/vhosts/mydomain.com/mydomain.com (code=exited, status=203/EXEC)
 Main PID: xx (code=exited, status=203/EXEC)

Mai xx xx:xx:xx xxxx.xx.xx xx[1]: golangweb.service: Failed with result 'exit-code'.
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

有人知道为什么会这样吗?

ExecStart 的第一个参数需要是一个可执行文件。看起来你已经将它设置为一个目录。如果您尝试在 shell 提示符下键入 /var/www/vhosts/mydomain.com/mydomain.com,您会看到类似的行为:您不能 运行 目录。

可以设置:

WorkingDirectory=/var/www/vhosts/mydomain.com/mydomain.com
ExecStart=/usr/bin/go run main.go

或者,您可以编译代码 (go build),然后将 ExecStart 设置为已编译二进制文件的完整路径:

ExecStart=/var/www/vhosts/mydomain.com/mydomain.com/compiledprogramname