Create a custom image function

更新时间:
复制 MD 格式

If the built-in runtimes provided by Function Compute do not meet your business requirements, you can create a function using a custom image. This topic describes how to create a function that uses a custom image in the Function Compute console or using Serverless Devs.

Notes

  • To create a function that uses a custom image, you must use an image from a Container Registry repository that is in the same region and belongs to the same Alibaba Cloud account as the function. For Mac computers that have Apple chips or other machines that use the ARM architecture, you must specify the build platform as Linux/Amd64 when you build the image. An example command is docker build --platform linux/amd64 -t $IMAGE_NAME ..

  • When Function Compute parses the domain name of a Container Registry (ACR) Enterprise Edition image, it uses the access IP address that is resolved by either the default Domain Name System (DNS) server of the VPC configured for the image repository instance or automatically by PrivateZone. The following scenarios are supported:

    • Scenario 1: If no IP address is designated as the Default DNS in the Access IP list on the Access Control page of the ACR Enterprise Edition instance, PrivateZone automatically resolves all IP addresses in the list. You can use any VPC configuration.

      image

    • Scenario 2: If an IP address is marked as Default DNS in the Access IP list on the Access Control page of an ACR Enterprise Edition instance, that IP address is resolved by the default DNS server of its VPC. As shown in the following figure, this means you can select only the first VPC.

      image

  • When you use an Enterprise Edition instance, you can select only non-accelerated images. Each time you update the image configuration of a function, a new accelerated image is generated based on the selected original image. If an accelerated image already exists, it is overwritten. Do not delete the original image or the accelerated image. Otherwise, function invocations are affected.

  • If the image that you specified in the function configuration changes, you must promptly update your function. Otherwise, function invocations will fail.

    • Make sure that the original image exists. Otherwise, the function enters the Failed state and cannot be invoked. Function Compute caches your function to accelerate cold starts, but the original image is still required during invocations.

    • Make sure that the image you use in a function is not overwritten. If the image is overwritten with a different digest, you must promptly redeploy your function with the latest image information. Function Compute records the image version tag and digest that you select when you create or update a function. If the digest of your image version is updated elsewhere, function invocations will fail.

Prerequisites

Create a function in the console

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click Create Function.

  3. In the dialog box that appears, follow the prompts to select a GPU Function type for your scenario, and then click Create GPU Function.

  4. On the Create GPU Function page, set the following parameters and click Create.

    After the function is created, you can view and update it on the function list page.

Note

When you update a function, you can only change the configured listener port. You cannot delete or add listener ports. If you configure a listener port when you create a function but do not specify a listener port when you update the function, the listener port that is configured during creation is retained.

Create a function using Serverless Devs

You can use Serverless Devs to build and push a container image, and then deploy a function with a single click.

  1. Run the following command to initialize the project.

    sudo s init

    Follow the on-screen instructions to select an Alibaba Cloud account, a custom image template, and a programming language. This topic uses Node.js as an example. Then, set the project name, select the region where you want to deploy the project, and enter your ACR image information.

    image

  2. Run the following command to go to the project directory.

    cd start-fc3-custom-container-nodejs
  3. Edit the s.yaml file. For more information about the parameters in the YAML file, see YAML specifications.

    The following provides an example.

    In this example, image specifies your ACR image. You must replace <your namespace>, <your image>, and <your tag> with the actual namespace name, image repository name, and image version, respectively. If you entered the correct ACR image when you initialized the project in Step 1, you do not need to modify this parameter.

    edition: 3.0.0
    name: hello-world-app
    # access: The AccessKey pair that is required for the current application.
    # For more information about how to configure the AccessKey pair, see: https://www.serverless-devs.com/serverless-devs/command/config
    # For more information about the order in which AccessKey pairs are used, see: https://www.serverless-devs.com/serverless-devs/tool#密钥使用顺序与规范
    access: "default"
    
    vars: # Global variables
      region: "cn-hangzhou"
    
    resources:
      hello_world:
        # If you want to perform operations only on the hello_world service, you can add hello_world to the command. Example:
        # Build only the hello_world service: s hello_world build
        # If you run the s build command without hello_world, the tool builds all service modules at the same level as hello_world (if other peer modules exist, such as the commented-out next_function below) in a specific order.
        component: fc3 # Component name
        actions:       # Custom execution logic
          pre-deploy: # Run before deployment
            - component: fc3 build --dockerfile ./code/Dockerfile  # The component to run. Format: "component: Component name Command Parameter"
        props:
          region: ${vars.region}              # For more information about how to use variables, see: 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 ACR image. Replace <your namespace>, <your image>, and <your tag> with your actual namespace name, image repository name, and image version.
          # triggers:
          #   - triggerName: httpTrigger # Trigger name
          #     triggerType: http # Trigger type
          #     description: 'xxxx'
          #     qualifier: LATEST # The version of the service to trigger
          #     triggerConfig:
          #       authType: anonymous # Authentication type. Valid values: anonymous and function.
          #       disableURLInternet: false # Specifies whether to disable public network access to the URL.
          #       methods: # The supported request methods for the HTTP trigger. Valid values: GET, POST, PUT, DELETE, and HEAD.
          #         - GET
          #         - POST
  4. Run the following command to deploy the project.

    sudo s deploy

    The following sample 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
  5. Run the following command to test the function.

    sudo s invoke -e "{\"key\":\"val\"}"

    The following sample 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

References

  • When you use a function that has a custom image, the base environment on which the container image depends requires extra time for data download and decompression. To reduce the cold start time, see Best practices for optimizing the cold start of Function Compute.

  • You can also call an API operation to create a function. For more information, see CreateFunction.

  • For more information about the scenarios of and differences among the built-in runtimes, custom runtimes, and custom images provided by Function Compute, see Select a function runtime.