> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lightning-go.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Graceful Shutdown

> Start your server with Run() or RunGraceful() and stop it cleanly on SIGINT/SIGTERM.

Lightning provides two ways to start your server: `app.Run()` for simple cases and `app.RunGraceful()` when you need to finish in-flight requests before the process exits.

## `app.Run()`

`app.Run()` starts the server and blocks until the server encounters an error. Pass an address string to bind to a specific host and port.

```go theme={null}
app.Run(":8080")           // listen on all interfaces, port 8080
app.Run("127.0.0.1:9000") // listen on localhost only
```

<Note>
  When you call `app.Run()` with no arguments, the server listens on `:6789` by default. You can also override the port by setting the `PORT` environment variable.
</Note>

`app.Run()` does not handle OS signals. Sending `SIGINT` (Ctrl+C) or `SIGTERM` terminates the process immediately without waiting for active connections to complete.

## `app.RunGraceful()`

`app.RunGraceful(shutdownTimeout, address)` listens for `SIGINT` and `SIGTERM`. When either signal arrives, it calls the underlying server's shutdown method and waits up to `shutdownTimeout` seconds for active connections to finish.

```go theme={null}
app.RunGraceful(10, ":8080") // 10-second shutdown window
```

If `shutdownTimeout` is zero or negative, it defaults to 5 seconds.

Like `app.Run()`, the address argument is optional — omit it to fall back to `:6789`.

## `app.Shutdown()`

Call `app.Shutdown()` to trigger a graceful shutdown programmatically (for example, from a signal handler you manage yourself or from a test).

```go theme={null}
app.Shutdown()
```

Calling `Shutdown()` before the server has started is a no-op.

## Complete Example

```go theme={null}
package main

import (
    "github.com/go-labx/lightning"
)

func main() {
    app := lightning.DefaultApp()

    app.Get("/ping", func(ctx *lightning.Context) {
        ctx.JSON(lightning.StatusOK, lightning.Map{"message": "pong"})
    })

    // Start with a 10-second graceful shutdown window.
    // Blocks until SIGINT or SIGTERM is received, then waits up to
    // 10 seconds for in-flight requests to complete.
    if err := app.RunGraceful(10, ":8080"); err != nil {
        app.Logger.Warn("server error: %v", err)
    }
}
```

When you stop the process with Ctrl+C or `kill <pid>`, you will see:

```
Received signal interrupt, shutting down gracefully...
Server stopped gracefully
```

<Tip>
  Prefer `RunGraceful` in production so that long-running requests (database queries, file uploads) are not cut off mid-flight during deployments or container restarts.
</Tip>
