I
I
impressive172020-10-27 17:17:34
go
impressive17, 2020-10-27 17:17:34

How to run a program as a daemon in Go?

I have a main.go file. How can I run it as a daemon?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2020-10-27
@EvgenyMamonov

If you do it like this ./main &, then when the ssh session ends, the daemon itself will fall off.
It all really depends on the OS.
If we talk about Linux and the simplest way, then you can do this
nohup ./main > error.log 2>&1 &
. This method is suitable for any binaries that do not fork, i.e. behave the same way as Go's http ListenAndServe.
The second option is to run the service through systemd or init.d depending on which one your Linux has.
I prefer this option, especially when you can not use Docker (for example, on virtual machines with Virtuozzo).
For systemd (for example, on CentOS), you can create a file /etc/systemd/system/yourservice.conf with something like this

[Unit]
Description=YourServie
After=network.target
After=syslog.target

[Service]
User=nobody # user ID под которым должен работать ваш демон
Group=nobody
Type=simple
WorkingDirectory=/opt/yourservice
ExecStart=/opt/yourservice/yourservice >> /var/log/yourservice.log 2>&1
Restart=always

[Install]
WantedBy=multi-user.target

The third option is to use Docker, there are a lot of instructions on the Internet, if this option is relevant - write, I will help you find a normal one.
The fourth option, which is usually used in software like Nginx, etc.
In the general case, you need to:
- spawn a new process, i.e. do a fork (call a system call)
- configure stdout, stderr output to files (optional)
- "get rid of the session" call a setsid system call
- make chdir where necessary
- configure SIGINT, SIGTERM signal processing to be able to shut down correctly or re-read configs
Maybe I missed something in this list, I haven’t made daemons this way for a long time, I use either Docker or systemd / init.d, it’s much easier :)
I can also add that the 4th option for Go is considered an anti-pattern.
Here https://socketloop.com/tutorials/golang-daemonizin... there is an example, although it is not very successful, there are a lot of nuances.

P
Papa, 2020-10-27
Stifflera @PapaStifflera

A lot depends on the OS.
With such a formulation of the question, there is only one answer - the same as in any PL.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question