45

What is the proper way to start a Go program as a daemon in Ubuntu ? I will then monitor it with Monit. Should I just do something like:

go run myapp.go &

Are there things specific to Go that I should take into account ?

Blacksad
  • 14,906
  • 15
  • 70
  • 81
  • if there is no urgent need of recompiling your app everytime you should build it once and run it as it is with other compiled languages. see abbot's answer – Bort Apr 09 '12 at 09:28

2 Answers2

46

You should build an executable for your program (go build) and then either write a script for upstart and it will run your program as a daemon for you, or use an external tool like daemonize. I prefer the latter solution, because it does not depend on a system-dependent upstart. With daemonize you can start your application like

daemonize -p /var/run/myapp.pid -l /var/lock/subsys/myapp -u nobody /path/to/myapp.exe

This will give you a well-behaving unix daemon process with all necessary daemon preparations done by daemonize.

abbot
  • 27,408
  • 6
  • 54
  • 57
  • 3
    This is how we've done it at work. Goroutines complicate daemonization in process. On RHEL we use standard Sys V start/stop/restart scripts. Elsewhere you'd want to use whatever the target OS uses...upstart, etc. On Windows we have a small Windows service written in C# that does the same thing there. – Nate Apr 09 '12 at 04:52
  • 1
    Thank you. Would you mind sharing your C#-Code, Nate? – Atmocreations Feb 07 '16 at 12:41
  • There's also https://github.com/fiorix/go-daemon as an alternative, specifically built for Go programs. – fiorix Apr 15 '16 at 14:13
10

There is a bug report regarding the ability to daemonize from within a Go program: http://code.google.com/p/go/issues/detail?id=227

But if what you are after is just detaching from the process I have seen recommendations to either do one of the following:

nohup go run myapp.go & 

or

go run myapp.go & disown

You can also make use of a process manager, like writing an init.d, Startup, or using something like Supervisor, which I personally really like.

jdi
  • 90,542
  • 19
  • 167
  • 203