This topic describes how to implement lifecycle hooks for function instances in a custom container runtime for which the web server mode is configured.

Limits

A custom container runtime for which the web server mode is not enabled does not support the Initializer, PreFreeze, and PreStop hooks. Function Compute sends a SIGTERM signal to instances only when the client actively cancels a request. If necessary, you can capture the SIGTERM signal in the container business logic.

Lifecycle hooks

After you configure a lifecycle hook for a function instance, Function Compute invokes the hook when a related lifecycle event for the instance occurs. The following lifecycle hooks can be configured for a function instance: Initializer, PreFreeze, and PreStop. For more information, see Function instance lifecycle.

The following table describes the Initializer hook. The PreFreeze and PreStop hooks are used in the same manner as the Initializer method.

PathRequestExpected response
(Optional) POST /initialize

Request body: none.

Request header: common request headers. For more information, see Common request headers in Function Compute.

Response body: the return value of the Initializer hook.
StatusCode
  • 200: succeeded
  • 404: failed
Sample code for initialize in Python:
@app.route('/initialize', methods=['POST'])
def init_invoke():
    rid = request.headers.get(x-fc-request-id)
    print("FC Initialize Start RequestId: " + rid)
    # do your things
    print("FC Initialize End RequestId: " + rid)
    return "OK"
(Optional) GET /pre-freezeResponse body: the return value of the PreFreeze hook.
StatusCode
  • 200: succeeded
  • 404: failed
(Optional) GET /pre-stopResponse body: the return value of the PreStop hook.
StatusCode
  • 200: succeeded
  • 404: failed
If you want to use the Initializer hook in a custom runtime, you need to implement the logic that corresponds to the /initialize path and the POST method in your HTTP server. You can refer to the sample code for initialize in the preceding table.
Important If you do not configure the Initializer hook for the function, the /initialize path does not need to be implemented. Even if the /initialize path is implemented by the HTTP server, you cannot invoke or execute the /initialize logic in the code.