astropanic astropanic - 1 year ago 214
Linux Question

How I should run my Golang process in background?

This question is not strictly programming related, but for sure important for programmers.

I wrote a simple smtp server, when I run it from console all is fine, except it is blocking the command line.

I know I can run it via

nohup ... &

or via screen / tmux etc

But the question is, how should I implement my program it runs in the background and it will be a pleasure for a system administrator to set it up and manage the process ?

Some guys with far more experience than me, at golang-nuts, wrote, they don't use fork etc, and use some "wrapper" in form from monit etc.

The target platform is Debian based, all other stuff on the box are init.d based.

Any good resources for that topic or sources of a well written example project ?

Answer Source

As Nick mentioned Supervisord is a great option that has also worked well in my experience.

Nick mentioned problems with forking- forking itself works fine AFAICT. The issue is not forking but dropping privileges. Due to the way the Go runtime starts the thread pool that goroutines are multiplexed over (when GOMAXPROX > 1), the setuid systemcall is not a reliable way to drop permissions.

Instead, you should run your program as a non-privileged user and use the setcap utility to grant it the needed permissions.

For example, to allow binding to a low port number (like 80) run will need to run setcap once on the executable: sudo setcap 'cap_net_bind_service=+ep' /opt/yourGoBinary

You may need to install setcap: sudo aptitude install libcap2-bin

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download