Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep running Go Server as background process

I want to keep my Golang language web server working regardless of an error happens or not. How to keep running it always?

like image 711
Murtadha S. Avatar asked Apr 27 '17 06:04

Murtadha S.


2 Answers

We have to inspect an always-on server from 2 perspectives:

  1. Handle / tolerate errors that occur during serving requests
  2. Restart the server app if it crashes or gets killed

For the first, you don't have to do anything special. If your handler panics, it will not blow your whole server, the http server will recover from that. It will only stop serving that specific request. Of course you can create your own handler which calls other handlers and recovers on panic and handle it in an intelligent way, but this is not a requirement.

One thing to note here: a Go app ends when the main goroutine ends (that is: the main() function returns). So even though goroutines serving requests are protected, if your main goroutine would end (e.g. panic), your app would still exit.

For the second, it's not really Go related. For example if you're on linux, simply install / register your compiled Go executable as a service, properly configured to have it restarted should it exit or crash.

For example in Ubuntu which uses systemd for service configuration, the following minimal service descriptor would fulfill your wishes:

[Unit]
Description=My Always-on Service

[Service]
Restart=always
Type=simple
ExecStart=/path/to/your/app -some=params passed

[Install]
WantedBy=multi-user.target

Put the above text in a file e.g. /etc/systemd/system/myservice.service, and you can enable and start it with:

sudo systemctl enable myservice.service 
sudo systemctl start myservice.service 

The first command places a symlink to the proper folder to have it auto-started on system startup. The second command starts it right now.

To verify if it's running, type:

sudo systemctl status myservice.service 

(You can omit the .service extension in most cases.)

Now whenever your app crashes, or the OS gets restarted, your app will be automatically started / restarted.

Further reading and tutorials for systemd:

How To Use Systemctl to Manage Systemd Services and Units

Systemd Essentials: Working with Services, Units, and the Journal

Convert "run at startup" script from upstart to systemd for Ubuntu 16

systemd: Writing and Enabling a Service

like image 198
icza Avatar answered Sep 29 '22 08:09

icza


There are few things which you can do. Such as,

  1. If you are worrying about panics, the simply run the server as a background process. user@terminal# go run server.go &
  2. Otherwise, for server crashes, you may write Shell script to re-run it and kill the old process.
like image 30
shivendra pratap singh Avatar answered Sep 29 '22 09:09

shivendra pratap singh