Use the Function Compute Go SDK to create a custom container function from a container image.
Prerequisites
Before you begin, ensure that you have:
Go installed and the
github.com/aliyun/fc-go-sdkpackage availableA container image pushed to a registry accessible from Function Compute
The
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables set in your local environmentThe
ACCOUNT_IDenvironment variable set to your Alibaba Cloud account ID
The AccessKey pair of an Alibaba Cloud account has full access to all API operations. Use a RAM user with limited permissions to call API operations or perform routine O&M. Never hardcode your AccessKey ID or AccessKey secret in project code. In the runtime environments of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions.
SDK example
The following example creates a function with the custom-container runtime. Setting CustomContainerConfig.AccelerationType to Default enables image pull acceleration.
package main
import (
"fmt"
"os"
"github.com/aliyun/fc-go-sdk"
)
func main() {
// Create an FC client using credentials from environment variables
fcClient, err := fc.NewClient(
fmt.Sprintf("%s.cn-shanghai.fc.aliyuncs.com", os.Getenv("ACCOUNT_ID")),
"2016-08-15",
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
)
if err != nil {
panic(err)
}
// Create a custom container function with image pull acceleration enabled
respC, err := fcClient.CreateFunction(
fc.NewCreateFunctionInput("demo-service").
WithFunctionName("demo-function").
WithHandler("bootstrap").
WithRuntime("custom-container").
WithCustomContainerConfig(
fc.NewCustomContainerConfig().
WithImage("registry.cn-shenzhen.aliyuncs.com/fc-demo/nodejs-express:v1"),
),
)
if err != nil {
panic(err)
}
fmt.Printf("FC CreateFunction response: %+v\n", *respC)
}Replace registry.cn-shenzhen.aliyuncs.com/fc-demo/nodejs-express:v1 with your own container image URI.
How it works
The example does the following:
Creates an FC client pointed at the
cn-shanghaiendpoint, authenticated using credentials from environment variables.Submits a
CreateFunctionrequest with thecustom-containerruntime, specifying a container image and thebootstraphandler.Sets
AccelerationTypetoDefault, which enables image pull acceleration.Prints the API response on success, or panics on error.