在Ubuntu上作为systemctl服务运行时Go找不到文件

Tar*_*ych 3 go systemctl

我有一个Go应用,正在尝试将其作为systemctl服务运行(Ubuntu 18.04)。

我正在使用godotenv

func init() {
    var env map[string]string
    env, err := godotenv.Read()
    if err != nil {
        panic(err)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的.env文件位于可执行文件所在的目录中。

我创建了一个service文件:

[Unit]
Description=my go app
Requires=local-fs.target
After=rsyslog.service

[Service]
Type=forking
GuessMainPID=no
StandardInput=null
ExecStart=/var/path/to/my/app/main

[Install]
WantedBy=default.target
Run Code Online (Sandbox Code Playgroud)

执行完sudo systemctl start my-go-app.service之后sudo systemctl status my-go-app.service,我将这些记录在日志中:

正在启动我的应用程序...
恐慌:打开.env:没有此类文件或目录

怎么了?

main直接执行时,不存在此类问题。

Tho*_*mas 5

我的.env文件位于可执行文件所在的目录中。

然后,您需要配置您的工作目录以匹配:

[Service]
...
WorkingDirectory=/var/path/to/my/app
Run Code Online (Sandbox Code Playgroud)

记住systemctl daemon-reload在更改任何单位文件后运行。