英文:
Problem with a Golang webapp and system service
问题
我正在尝试在Ubuntu上使用gin框架创建一个Golang服务器。在使用go build构建后,在终端中执行时,它可以正常工作,并且在本地也能正常工作。
Systemd
Description=goapp
[Service]
Type=simple
Restart=always
RestartSec=5s
ExecStart=/home/.../goapp/main
[Install]
WantedBy=multi-user.target
我得到了以下错误信息
goapp.service - rediate
Loaded: loaded (/lib/systemd/system/goapp.service; disabled; vendor preset: enabled)
Active: activating (auto-restart) (Result: exit-code) since Thu 2022-09-29 08:14:10 UTC; 66ms ago
Process: 21628
ExecStart=/home/.../go/goapp/main (code=exited, status=2)
Main PID: 21628 (code=exited, status=2)
CPU: 9ms
英文:
I am trying to create a Golang server using the gin framework on ubuntu. It works fine when it is executed in the terminal after building it with go build and equally works well locally.
Systemd
Description=goapp
[Service]
Type=simple
Restart=always
RestartSec=5s
ExecStart=/home/.../goapp/main
[Install]
WantedBy=multi-user.target
I got this error
goapp.service - rediate
Loaded: loaded (/lib/systemd/system/goapp.service; disabled; vendor preset: enabled)
Active: activating (auto-restart) (Result: exit-code) since Thu 2022-09-29 08:14:10 UTC; 66ms ago
Process: 21628
ExecStart=/home/.../go/goapp/main (code=exited, status=2)
Main PID: 21628 (code=exited, status=2)
CPU: 9ms
答案1
得分: 2
Go是一种编译语言。你需要使用go build
命令将你的代码构建成一个可执行的二进制文件,然后通过在单元文件中使用ExecStart
属性来指定二进制文件的路径,将其提供给systemd。
请参考Go文档,特别是编译和安装应用程序部分,了解更多关于如何编译你的应用程序的信息。
在你的示例中,你使用了ExecStart=/home/.../goapp/main.go
,这告诉systemd运行源代码文件。该文件不是可执行文件,也不被操作系统所理解,因此无法执行,导致systemd单元失败。
英文:
Go is compiled language. You need to build your code into an executable binary file using go build
command and then give path to binary file to systemd via ExecStart
property in unit file.
See Go Documentation and specifically Compile and install the application section to find out more about how to compile your application.
In your example you have ExecStart=/home/.../goapp/main.go
which is telling systemd to run source code file. That file is not executable and understood by operating system so it fails to execute and systemd unit fails because of that.
答案2
得分: 0
将工作目录添加到systemd可以修复此错误。
描述=goapp
[Service]
Type=simple
Restart=always
RestartSec=
WorkingDirectory=/home/.../goapp
ExecStart=/home/.../goapp/main
[Install]
WantedBy=multi-user.target
英文:
Adding a working directory to the systemd fix this error.
Description=goapp
[Service]
Type=simple
Restart=always
RestartSec=
WorkingDirectory=/home/.../goapp
ExecStart=/home/.../goapp/main
[Install]
WantedBy=multi-user.target
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论