Golang : How to run Golang application such as web server in the background or as daemon?
Problem :
You have completed your Golang program and want to run it as a background process or daemon. For example, you want your Web server to run as a service.
Solutions :
Depending on the operating system your program is sitting on, these are some of the most common examples :
CentOS/Ubuntu or Linux/Unix in general :
>nohup ./myexecutable &
or
>nohup ./myexecutable & disown
The nohup
command tells the shell to ignore the HANGUP signal and the &
command tells the shell to run the program in the background. To bring the program back to the foreground, issue this command :
>fg %1
and you can press Control-Z to kill it.
In the event you want to kill the process from command line, you can find out the PID
(process ID) with
>ps -ef | grep <your program name>
For example :
>ping www.yahoo.com &
>ps -ef | grep yahoo
> 501 903 1 0 6:10PM ?? 0:00.01 ping www.yahoo.com
then you can issue the command to kill process ID 903
>kill 903
Windows :
Register your Golang program with NSSM (the Non-Sucking Service Manager). For example :
nssm install YourProgram c:\YourProgram.exe
and to delete your program from the Windows service register, use the native service control :
sc delete YourProgram
NOTE : Your Golang program can write to Windows Event Log with this package http://godoc.org/code.google.com/p/winsvc
You might want to explore how to create daemonize Golang program easily with this tutorial :
https://www.socketloop.com/tutorials/golang-terminate-stay-resident-or-daemonize-your-program
See also : Golang : Terminate-stay-resident or daemonize your program?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Null and nil value
+4.8k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+4.8k Golang : Convert lines of string into list for delete and insert operation
+14.1k Golang : How to filter a map's elements for faster lookup
+6.7k Golang : Takes a plural word and makes it singular
+17k Golang : Get future or past hours, minutes or seconds
+11.7k Golang : Get remaining text such as id or filename after last segment in URL path
+62.3k Golang : Convert HTTP Response body to string
+18.1k Golang : Example for RSA package functions
+9.2k Golang : Read file with ioutil
+33.4k Golang : Create x509 certificate, private and public keys
+22.5k Golang : Test file read write permission example