If standard runtimes in Function Compute cannot meet your business requirements, you can create Custom Container functions. This topic describes how to create a Custom Container function in the Function Compute console or by using Serverless Devs.
Usage notes
To create a Custom Container function in Function Compute, you must use an Alibaba Cloud Container Registry image that resides in the same region as your function and belongs to the same account. For computers that run on ARM-based chips, such as Mac computers that run on Apple chips, you must specify the compilation platform of the image as linux/amd64 when you build the image. For example, run the
docker build --platform linux/amd64 -t $IMAGE_NAME .
command.Function Compute uses the default virtual private cloud (VPC) IP address of your image repository or the IP addresses resolved by Alibaba Cloud DNS PrivateZone to resolve the domain name of a container image in Container Registry Enterprise Edition. The following items describe the scenarios:
Scenario 1: If Default Resolution is not displayed for IP addresses in the Visit IP column on the Access Control page of a Container Registry Enterprise Edition instance, all IP addresses in the list are automatically resolved by Alibaba Cloud DNS PrivateZone. In this case, you can use any VPC.
Scenario 2: If Default Resolution is displayed for an IP address in the Visit IP column on the Access Control page of a Container Registry Enterprise Edition instance, the IP address is a default resolved VPC IP address. For example, in the example shown in the following figure, you must use the first VPC.
When you use a Container Registry Enterprise Edition instance, you can select only non-accelerated images. Each time you update the image configurations of a function, the latest accelerated image is generated based on the newly selected original image. If an accelerated image exists, the existing image is overwritten. Do not delete original images or accelerated images. Otherwise, function invocations are affected.
Make sure that you update your function in a timely manner if any change occurs in the configured image in your function. Otherwise, the function fails to be invoked.
Make sure that the original image exists. Otherwise, the function enters the Failed state and cannot be invoked. Function Compute automatically caches your function to accelerate cold starts. However, the invocation of your function still relies on the original image of your function.
Make sure that the image used in your function is not overwritten. If the image digest is overwritten, use the latest image information to redeploy your function. Function Compute records the tag and digest of the image version that you select when you create and update function configurations. If the image version is updated to another digest by another entity, the function fails to be invoked.
Before you start
Container Registry
Create a Container Registry Enterprise Edition instance
NoteYou can create a Container Registry Personal Edition or Container Registry Enterprise Edition instance. We recommend that you use Container Registry Enterprise Edition instance to create a function.
Container Registry Personal Edition is provided to individual developers. Individual developers are allocated a limited free quota during the public preview period. Alibaba Cloud does not provide service level agreement (SLA) promises or make compensation thereupon and has limits on using the edition. For more information about the limits, see Create a Container Registry Personal Edition instance.
Serverless Devs (required only if you use Serverless Devs to create a function)
Install Serverless Devs and dependencies
NoteYou must install Docker of version 19.03 or later.
Create a function in the Function Compute console
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click Create Function.
On the Create Function page, select Custom Container Image and follow the on-screen instructions to configure parameters. After you configure the parameters, click Create. The following items describe parameters in each section:
Basic Settings: Specify the function name.
Image configurations: Configure the image that is used to create the function.
Parameter
Description
Image Selection Mode
Specify a method to select the image. You can use a sample image or your own image to create a function.
Use Sample Images: Select a built-in sample image of Function Compute.
Use Container Registry Images: Use a Container Registry image. Click Select a Container Registry image below Container Image. In the Select Container Image panel, configure the Container Image Instance and Container Registry Repository parameters. Among the images that appear, find the desired image and click Select in the Actions column.
NoteYou cannot use public images from Container Registry that belong to another account to create a function.
Make sure that you update your function in a timely manner if any change occurs in the configured image in your function. Otherwise, the function fails to be invoked. For more information, see Usage notes.
If you use a Container Registry Enterprise Edition instance, you can select only a non-accelerated image. Do not delete the original image or accelerated image. Otherwise, function invocations are affected. For more information, see Usage notes.
Startup Command
Specify the startup command of the container. If you do not configure this parameter, the ENTRYPOINT or CMD instruction in the image is used.
Listener Port
Specify the port on which the HTTP server in the container image listens. The default port is 9000.
Advanced Settings: Configure advanced settings, such as the execution timeout period and handler of your function. The following table describes the parameters in this section:
Parameter
Description
GPU Acceleration
Specify whether to use GPU-accelerated instances based on your business requirements. By default, elastic instances instead of GPU-accelerated instances are used. For more information, see Instance types and usage modes. For information about the billing of each instance type, see Billing overview. Valid values:
Enable GPU
Disable GPU
Specifications
Enable GPU
Select a GPU memory size from the GPU Memory Size drop-down list based on your business requirements. Function Compute auto populates the vCPU Capacity and Memory Capacity fields based on the GPU memory size you select. Only specific vCPU and memory sizes are allowed for each GPU size.
Disable GPU
Specify vCPU Capacity and Memory Capacity based on your business requirements.
For information about the billing of resources, see Billing overview.
NoteThe ratio of vCPU to memory capacity (in GB) must be from 1:1 to 1:4.
Size of Temporary Disk
Select a disk size based on your business requirements. Function Compute provides a free disk capacity of 512 MB. For more information, see Billing overview.
Execution Timeout Period
Specify the timeout period for function executions. The default value is 60 seconds. The maximum value is 86,400 seconds. We recommend that you set this parameter to 600 seconds.
NoteIf the execution time of the function exceeds the specified timeout period, the function fails to be executed. If you need a longer timeout limit, join the DingTalk group 64970014484 for technical support.
Instance Concurrency
Specify the concurrency of function instances. For more information, see Configure instance concurrency.
Time Zone
Specify the time zone of the function. After you select the time zone of your function, the environment variable TZ is automatically added for the function. The value of the variable is the time zone that you select.
Function Role
Create a role for your function and grant the minimum required permissions to the role if your code logic needs to access other Alibaba Cloud services. For more information, see Grant Function Compute permissions to access other Alibaba Cloud services.
Access to VPC
Specify whether to allow the function to access VPC resources. For more information, see Configure network settings.
VPC
This parameter is required if you set Access to VPC to Yes. Create a VPC or select the ID of an existing VPC that you want to access from the drop-down list.
vSwitch
This parameter is required if you set Access to VPC to Yes. Create a vSwitch or select the ID of an existing vSwitch from the drop-down list.
Security Group
This parameter is required if you set Access to VPC to Yes. Create a security group or select an existing security group from the drop-down list.
Allow Default NIC to Access Internet
Specify whether to allow the function to access the Internet through the default network interface controller (NIC). If you select No, the function cannot access the Internet through the default NIC of Function Compute.
ImportantIf you use a static public IP address, you must set Allow Default NIC to Access Internet to No. Otherwise, the configured static public IP address does not take effect. For more information, see Configure static public IP addresses.
Logging
Specify whether to enable the logging feature. Valid values:
Enable: enables the logging feature. After the logging feature is enabled, you can view function invocation logs, which are stored in Simple Log Service and can be queried based on your businesses requirements.
Disable: does not enable the logging feature.
Environment Variables: Configure the environment variables in the runtime of your function. For more information, see Configure environment variables.
After the function is created, you can view and update the function in the function list.
When you update the function after it is created, you can change the specified listening port. However, you cannot delete or add extra listening ports. If a listening port is specified when you create the function, the listening port is retained when you update the function if you do not specify another listening port.
Use Serverless Devs to create a function
You can use Serverless Devs to build and push container images and deploy functions with a few clicks.
Run the following command to initialize your project:
sudo s init
On the page that appears, specify an Alibaba Cloud account, a custom container template, and a programming language. In this example, Node.js is used. Configure the project name, the region where the project is deployed, and enter your Container Registry image.
Run the following command to go to the project directory:
cd start-fc3-custom-container-nodejs
Edit the
s.yaml
file. The following sample code provides an example: For more information about parameters in a YAML file, see YAML syntax.The following sample code shows an example.
In the example,
image
indicates your Container Registry image. Replace <your namespace>, <your image>, and <your tag> with the actual values. If you have correctly configured your image in Step 1, you do not need to modify the values here.edition: 3.0.0 name: hello-world-app # access specifies the key information required by the current application. # For information about how to configure keys, visit https://www.serverless-devs.com/serverless-devs/command/config. # For more information about the sequence of keys, visit https://www.serverless-devs.com/serverless-devs/tool#. access: "default" vars: # The global variables region: "cn-hangzhou" resources: hello_world: # If you want to perform operations only on hello_world, you can add hello_world to the command line. Example: # Only build hello_world: s hello_world build. # If you run the s build command without adding hello_world, Serverless Devs performs the build operations on all business modules that are at the same level as hello_world in the current YAML file, such as the next_function module in the following comment. component: fc3 # The name of the component. actions: # The custom execution logic pre-deploy: # Run before deployment. - component: fc3 build --dockerfile ./code/Dockerfile # The component to be run, which follows the "component: Component name Command Parameter" format. props: region: ${vars.region} # For more information about how to use variables, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC. functionName: "start-nodejs-ufrz" runtime: "custom-container" description: 'hello world by serverless devs' timeout: 30 memorySize: 512 cpu: 0.5 diskSize: 512 code: ./code customContainerConfig: image: 'registry.${vars.region}.aliyuncs.com/<your namespace>/<your image>:<your tag>' # Your Container Registry image. Replace <your namespace>, <your image>, and <your tag> with the actual values. # triggers: # - triggerName: httpTrigger # The trigger name. # triggerType: http # The trigger type. # description: 'xxxx' # qualifier: LATEST # The function version. # triggerConfig: # authType: anonymous # The authentication type. Valid values: anonymous and function. # disableURLInternet: false # Specifies whether to disable access to the URL over the Internet. # methods: # The access methods supported by the HTTP trigger. Valid values: GET, POST, PUT, DELETE, and HEAD. # - GET # - POST
Run the following command to deploy the project:
sudo s deploy
The following output is returned:
Steps for [deploy] of [hello-world-app] ==================== DEPRECATED: The legacy builder is deprecated and will be removed in a future release. BuildKit is currently disabled; enable it by removing the DOCKER_BUILDKIT=0 environment-variable. Sending build context to Docker daemon 5.12kB Step 1/7 : FROM node:14-buster 14-buster: Pulling from library/node 2ff1d7c41c74: Already exists b253aeafeaa7: Already exists 3d2201bd995c: Already exists 1de76e268b10: Already exists d9a8df589451: Already exists 6f51ee005dea: Already exists 5f32ed3c3f27: Already exists 0c8cc2f24a4d: Already exists 0d27a8e86132: Already exists Digest: sha256:a158d3b9b4e3fa813fa6c8c590b8f0a860e015ad4e59bbce5744d2f6fd8461aa Status: Downloaded newer image for node:14-buster ---> 1d12470fa662 Step 2/7 : WORKDIR /usr/src/ ---> Running in 70a8e2e4d1ea Removing intermediate container 70a8e2e4d1ea ---> 0d67b8fa2901 Step 3/7 : COPY package*.json ./ ---> 09eb15f8770a Step 4/7 : RUN npm install ---> Running in 8ae492be973b Step 5/7 : COPY . . ---> 7560c7b14431 Step 6/7 : EXPOSE 9000 ---> Running in 66b38e54ced0 Removing intermediate container 66b38e54ced0 ---> f73cce48d2ae Step 7/7 : ENTRYPOINT [ "node", "server.js" ] ---> Running in 2fb2f83fd6c0 Removing intermediate container 2fb2f83fd6c0 ---> fe51ae71448c Successfully built fe51ae71448c Successfully tagged registry.cn-hangzhou.aliyuncs.com/z****/z****:latest [2024-01-29 16:33:06][INFO][hello_world] get instanceName= and region=cn-hangzhou from registry.cn-hangzhou.aliyuncs.com/z****/z**** [2024-01-29 16:33:06][INFO][hello_world] try to docker push registry.cn-hangzhou.aliyuncs.com/z****/z**** ... WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded Using default tag: latest The push refers to repository [registry.cn-hangzhou.aliyuncs.com/z****/z****] 85c1ec915b45: Pushed 37c36543a431: Pushed e4afd7f70434: Pushed 0d5f5a015e5d: Layer already exists 3c777d951de2: Layer already exists f8a91dd5fc84: Layer already exists cb81227abde5: Layer already exists e01a454893a9: Layer already exists c45660adde37: Layer already exists fe0fb3ab4a0f: Layer already exists f1186e5061f2: Layer already exists b2dba7477754: Layer already exists latest: digest: sha256:6bf1ed4119d197a46c99082577632957056cb625f2ee0276d2af53f60d22837d size: 2841 [hello_world] completed (688.45s) Result for [deploy] of [hello-world-app] ==================== region: cn-hangzhou cpu: 0.5 customContainerConfig: image: registry.cn-hangzhou.aliyuncs.com/z****/z**** resolvedImageUri: registry.cn-hangzhou.aliyuncs.com/z****/z****@sha256:6bf1ed4119d197a46c99082577632957056cb625f2ee0276d2af53f60d22837d description: hello world by serverless devs diskSize: 512 functionName: start-nodejs-ufrz handler: handler instanceConcurrency: 1 internetAccess: true lastUpdateStatus: Successful memorySize: 512 role: runtime: custom-container state: Active timeout: 30 A complete log of this run can be found in: /root/.s/logs/0129162246
Run the following command to debug the function:
sudo s invoke -e "{\"key\":\"val\"}"
The following output is returned:
Steps for [invoke] of [hello-world-app] ==================== ========= FC invoke Logs begin ========= FC Invoke Start RequestId: 1-65b764db-15eb737f-0c67ab5cd968 FC Invoke Start RequestId: 1-65b764db-15eb737f-0c67ab5cd968 hello world! FC Invoke End RequestId: 1-65b764db-15eb737f-0c67ab5cd968 Duration: 42.27 ms, Billed Duration: 43 ms, Memory Size: 512 MB, Max Memory Used: 47.77 MB ========= FC invoke Logs end ========= Invoke instanceId: c-65b764db-15fa2aa8-bc50f7839399 Code Checksum: undefined Qualifier: LATEST RequestId: 1-65b764db-15eb737f-0c67ab5cd968 Invoke Result: OK [hello_world] completed (4.96s) A complete log of this run can be found in: /root/.s/logs/0129164202
More information
If you want to use GPU-accelerated instances, you must create Custom Container functions. For more information about specifications of GPU-accelerated instances, see Create a web function.
If you use Custom Container functions, the base environment on which a container image depends requires additional time to download and decompress data. For information about how to accelerate cold starts, see Best practice for reducing cold start latencies.
You can also call the Function Compute API to create a function. For more information, see CreateFunction.
For information about the common scenarios and differences among built-in runtimes, custom runtimes, and Customer Container runtimes, see Selection of methods to create functions.