Evert
Evert

Reputation: 99523

Exiting go applications gracefully

I'm new to Go and I have a few small services running.

When I'm deploying a new version, I typically just upload the new binary, kill the existing process and start a new one.

I'm wondering if this is the correct thing to do, or if there is a better way to do this.

Upvotes: 8

Views: 8155

Answers (1)

codefreak
codefreak

Reputation: 7131

There's nothing wrong in killing the process, replacing and restarting. If you want to do some cleanup on exiting you may do following:

import(
   "fmt"
   "os"
   "os/signal"
   "syscall"
)

func main(){
   //work here

   go gracefulShutdown()
   forever := make(chan int)
   <-forever
}

func gracefulShutdown() {
    s := make(chan os.Signal, 1)
    signal.Notify(s, os.Interrupt)
    signal.Notify(s, syscall.SIGTERM)
    go func() {
        <-s
        fmt.Println("Sutting down gracefully.")
        // clean up here
        os.Exit(0)
    }()
}

If you do kill {pid} (without -9 switch), process will call gracefullShutdown function before terminating.

Upvotes: 17

Related Questions