2 min read

Running Golang program as systemd service in Ubuntu

Hướng dẫn chạy chương trình trên ubuntu bằng systemd service

devops linux

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

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

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

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

Restart syslog:

$ systemctl restart rsyslog.service

Active service

Running command as root:

$ systemctl daemon-reload
$ service my_api_service start
$ service my_api_service status

If you want to auto start your service after reboot:

$ systemctl enable my_api_service
$ systemctl start my_api_service

Tail the log file:

$ sudo tail -n 10 /var/log/my_api_service/output.log
EOF - Thanks for reading!
VIEW ALL POSTS