skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search