DEV Community

Nguyen Trung Duc
Nguyen Trung Duc

Posted on Edited on

Running Golang program as systemd service in Ubuntu

Test your binary file

Assum that you have golang binary file my-api-service located in folder /home/dev/my-app

So you can test your file if it can run as normal:

$ cd /home/dev/my-app
$ chmod +x my-api-service
$ ./my-api-service
Enter fullscreen mode Exit fullscreen mode

If it running success, go to next step

Create system service file

Create a file /etc/systemd/system/my_api_service.service as root user with below content:

[Unit]
Description=My API Service
ConditionPathExists=/home/dev/my-app
After=network.target

[Service]
Type=simple
User=dev
Group=dev

WorkingDirectory=/home/dev/my-app
Environment="YOUR_ENV_1=YOUR_ENV_1_VALUE"
Environment="YOUR_ENV_2=YOUR_ENV_2_VALUE"
ExecStart=/home/dev/my-app/my-api-service
Restart=on-failure
RestartSec=10

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=my-api-service

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

You can export more environment variables by adding row Environment="..."

Config rsyslog

Create folder for log:

mkdir /var/log/my_api_service
chown syslog:syslog /var/log/my_api_service
Enter fullscreen mode Exit fullscreen mode

Create config file at /etc/rsyslog.d/my_api_service.conf and paste below content:

if $programname == 'my-api-service' then
  /var/log/my_api_service/output.log
& stop
Enter fullscreen mode Exit fullscreen mode

Restart syslog:

$ systemctl restart rsyslog.service
Enter fullscreen mode Exit fullscreen mode

Active service

Running command as root:

$ systemctl daemon-reload
$ service my_api_service start
$ service my_api_service status
Enter fullscreen mode Exit fullscreen mode

If you want to auto start your service after reboot:

$ systemctl enable my_api_service
$ systemctl start my_api_service
Enter fullscreen mode Exit fullscreen mode

Tail the log file:

$ sudo tail -n 10 /var/log/my_api_service/output.log
Enter fullscreen mode Exit fullscreen mode

Read the root post at my site

Top comments (0)