Search code examples
gopm2

PM2-like process management solution for Golang applications?


Does Go have a process manager similar to PM2 for NodeJS?

Basic features of PM2:

  • Run application in background indefinitely, such as a server waiting for a request.
  • Restart application upon reboot.

Editor's note: PM2 offers an easy way to run a NodeJS application in the background forever, such as for a production server. Of course you can do this with the Linux operating system, using tools not specific to any particular programming language, and those answers are helpful. As Go can create executables, you don't really need a Go-language specific solution to this question.


Solution

  • Development Environment

    For development, you'd probably need process manager that also monitor the file changes and live-reload your server binary.

    I'm used to Godegansta's gin for such job for web server / api server development. There is also fresh, reflex and perhaps some others.


    Production Environment

    I'm using systemd to manage my Golang application process on Linux in production environment.

    Define the Unit

    My Unit File looks like this:

    [Unit]
    
    [Install]
    WantedBy=multi-user.target
    
    [Service]
    ExecStart=/usr/local/bin/<MY_GO_APP>
    WorkingDirectory=/home/user/<MY_GO_APP_HOME_DIR>
    User=<MY_GO_APP_USER>
    Restart=always
    RestartSec=5
    StandardOutput=syslog
    StandardError=syslog
    SyslogIdentifier=%n
    

    Create this file as /etc/systemd/system/my_app.service, then run:

    systemctl start my_app.service
    

    would automatically start the service. As configured, systemd will always restart your process if it stopped.

    Usual Operations

    To have it always on when the machine starts:

    systemctl enable my_app.service
    

    If you change your unit file after the first start or enable, you need to run:

    systemctl daemon-reload
    

    To see the status of the process, run:

    systemctl status my_app.service
    

    To see the STDOUT of the process, run:

    journalctl -f -u my_app.service
    

    For further help, please read the manual page.