DEV Community

Nguyen Trung Duc
Nguyen Trung Duc

Posted on

7 2

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay