Answer the question
In order to leave comments, you need to log in
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question