Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Developing an HTTP Function

Updated on 2024-08-07 GMT+08:00

Introduction

When developing an HTTP function using a custom image, implement an HTTP server in the image and listen on port 8000 for requests. (Do not change port 8000 in the examples provided in this section.) HTTP functions support only APIG triggers.

Step 1: Prepare the Environment

To perform the operations described in this section, ensure that you have the FunctionGraph FullAccess permissions, that is, all permissions for FunctionGraph. For more information, see Permissions Management.

Step 2: Create an Image

Take the Linux x86 64-bit OS as an example. (No system configuration is required.)

  1. Create a folder.
    mkdir custom_container_http_example && cd custom_container_http_example
  1. Implement an HTTP server. Node.js is used as an example. For details about other languages, see Creating an HTTP Function.

    Create the main.js file to introduce the Express framework, receive POST requests, print the request body as standard output, and return "Hello FunctionGraph, method POST" to the client.

    const express = require('express'); 
     
    const PORT = 8000; 
     
    const app = express(); 
    app.use(express.json());
     
    app.post('/*', (req, res) => { 
        console.log('receive', req.body); 
        res.send('Hello FunctionGraph, method POST');
    });
     
    app.listen(PORT, () => { 
      console.log(`Listening on http://localhost:${PORT}`); 
    });
  1. Create the package.json file for npm so that it can identify the project and process project dependencies.
    {
      "name": "custom-container-http-example",
      "version": "1.0.0",
      "description": "An example of a custom container http function",
      "main": "main.js",
      "scripts": {},
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
          "express": "^4.17.1"
      }
    }
    • name: project name
    • version: project version
    • main: application entry file
    • dependencies: all available dependencies of the project in npm
  2. Create a Dockerfile.
    FROM node:12.10.0
    
    ENV HOME=/home/custom_container
    ENV GROUP_ID=1003
    ENV GROUP_NAME=custom_container
    ENV USER_ID=1003
    ENV USER_NAME=custom_container
    
    RUN mkdir -m 550 ${HOME} && groupadd -g ${GROUP_ID} ${GROUP_NAME} && useradd -u ${USER_ID} -g ${GROUP_ID} ${USER_NAME}
    
    COPY --chown=${USER_ID}:${GROUP_ID} main.js ${HOME}
    COPY --chown=${USER_ID}:${GROUP_ID} package.json ${HOME}
    
    RUN cd ${HOME} && npm install
    
    RUN chown -R ${USER_ID}:${GROUP_ID} ${HOME}
    
    RUN find ${HOME} -type d | xargs chmod 500
    RUN find ${HOME} -type f | xargs chmod 500
    
    USER ${USER_NAME}
    WORKDIR /
    
    EXPOSE 8000
    ENTRYPOINT ["node", "main.js"]
    • FROM: Specify base image node:12.10.0. The base image is mandatory and its value can be changed.
    • ENV: Set environment variables HOME (/home/custom_container), GROUP_NAME and USER_NAME (custom_container), USER_ID and GROUP_ID (1003). These environment variables are mandatory and their values can be changed.
    • RUN: Use the format RUN <Command>. For example, RUN mkdir -m 550 ${HOME}, which means to create the home directory for user ${USER_NAME} during container building.
    • USER: Switch to user ${USER_NAME}.
    • WORKDIR: Switch the working directory to the / directory of user ${USER_NAME}.
    • COPY: Copy main.js and package.json to the home directory of user ${USER_NAME} in the container.
    • EXPOSE: Expose port 8000 of the container. Do not change this parameter.
    • ENTRYPOINT: Run the node main.js command to start the container. Do not change this parameter.
    NOTE:
    1. You can use any base image.
    2. In the cloud environment, UID 1003 and GID 1003 are used to start the container by default. The two IDs can be modified by choosing Configuration > Basic Settings > Container Image Override on the function details page. They cannot be root or a reserved ID.
    3. Do not change port 8000 in the example HTTP function.
  1. Build an image.

    In the following example, the image name is custom_container_http_example, the tag is latest, and the period (.) indicates the directory where the Dockerfile is located. Run the image build command to pack all files in the directory and send the package to a container engine to build an image.

    docker build -t custom_container_http_example:latest .

Step 3: Perform Local Verification

  1. Start the Docker container.
    docker run -u 1003:1003 -p 8000:8000 custom_container_http_example:latest
  1. Open a new Command Prompt, and send a message through port 8000. You can access all paths in the root directory in the template code. The following uses helloworld as an example.
    curl -XPOST -H 'Content-Type: application/json' -d '{"message":"HelloWorld"}' localhost:8000/helloworld
    The following information is returned based on the module code:
    Hello FunctionGraph, method POST
  1. Check whether the following information is displayed:
    receive {"message":"HelloWorld"}

    Alternatively, run the docker logs command to obtain container logs.

Step 4: Upload the Image

  1. Log in to the SoftWare Repository for Container (SWR) console. In the navigation pane, choose My Images.
  2. Click Upload Through Client or Upload Through SWR in the upper right corner.
  3. Upload the image as prompted.

  4. View the image on the My Images page.

Step 5: Create a Function

  1. In the left navigation pane of the management console, choose Compute > FunctionGraph. On the FunctionGraph console, choose Functions > Function List from the navigation pane.
  2. Click Create Function in the upper right corner and choose Container Image.
  3. Set the basic information.
    • Function Type: Select HTTP Function.
    • Function Name: Enter custom_container_http.
    • Container Image: Select the image uploaded to SWR.
    • Agency: Select an agency with the SWR Admin permission. If no agency is available, create one by referring to Creating an Agency.
  4. After the configuration is complete, click Create Function.

Step 6: Test the Function

  1. On the function details page, click Test. In the displayed dialog box, create a test event.
  2. Select apig-event-template, set Event Name to helloworld, modify the test event as follows, and click Create.
    {
        "body": "{\"message\": \"helloworld\"}",
        "requestContext": {
            "requestId": "11cdcdcf33949dc6d722640a13091c77",
            "stage": "RELEASE"
        },
        "queryStringParameters": {
            "responseType": "html"
        },
        "httpMethod": "POST",
        "pathParameters": {},
        "headers": {
            "Content-Type": "application/json"
        },
        "path": "/helloworld",
        "isBase64Encoded": false
    }

Step 7: View the Execution Result

Click Test and view the execution result on the right.

Figure 1 Execution result
  • Function Output: displays the return result of the function.
  • Log Output: displays the execution logs of the function.
  • Summary: displays key information of the logs.
    NOTE:

    A maximum of 2 KB logs can be displayed. For more log information, see Querying Function Logs.

Step 8: View Monitoring Metrics

On the function details page, click the Monitoring tab.

  • On the Monitoring tab page, choose Metrics, and select a time range (such as 5 minutes, 15 minutes, or 1 hour) to query the function.
  • The following metrics are displayed: invocations, errors, duration (maximum, average, and minimum durations), throttles, and instance statistics (reserved instances).

Step 9: Delete the Function

  1. On the function details page, choose Operation > Delete Function in the upper right corner.
  2. In the confirmation dialog box, enter DELETE and click OK to release resources in a timely manner.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback