Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a Go program as a daemon in Ubuntu?

Tags:

go

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 ?

like image 400
Blacksad Avatar asked Apr 08 '12 23:04

Blacksad


People also ask

How do I run a go program in Linux?

Add the Go install directory to your system's shell path. That way, you'll be able to run your program's executable without specifying where the executable is. Once you've updated the shell path, run the go install command to compile and install the package. Run your application by simply typing its name.

What is go daemon?

go-daemon is a tool in the Go Modules Packages category of a tech stack. go-daemon is an open source tool with 1.8K GitHub stars and 230 GitHub forks. Here's a link to go-daemon's open source repository on GitHub.


2 Answers

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.

like image 143
abbot Avatar answered Sep 29 '22 16:09

abbot


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.

like image 41
jdi Avatar answered Sep 29 '22 16:09

jdi