All Products
Search
Document Center

Function Compute:Quickly create a web application using web functions

Last Updated:Mar 04, 2025

You can easily build web applications and API services using web functions in Function Compute. Web functions are compatible with web frameworks in various popular languages such as Java SpringBoot, Python Flask, and Node.js Express, allowing you to quickly migrate existing applications. Function Compute manages the underlying computing resources for you. When the service is accessed through a browser or URL, the system automatically starts and scales instances as needed. When there is no access, it automatically destroys instances, and you only pay for the actual resource usage.

Overview of creating web functions

This topic describes how to deploy a Flask application using web functions in Function Compute. The overall process is as follows:

  1. Develop and test the web application: Use the sample code to create a project locally, edit and test the API code to ensure it functions properly. If you're migrating an existing application, you can skip this step.

  2. Generate a code package: Install the necessary dependency libraries into the local project directory, then package the project into a ZIP file for deployment to Function Compute.

  3. Upload and deploy the application: Configure the function creation parameters, then upload the code package to complete the function creation.

  4. Test the web function: Invoke the web function to verify the operation of the Flask application.

Prerequisites

Create an Alibaba Cloud account

To get started, create an Alibaba Cloud account and complete the real-name authentication process.

Activate Function Compute service

If you have registered an Alibaba Cloud account and completed real-name authentication after August 27, 2024, you can access the Function Compute product immediately without needing to activate it. Upon your first login to the Function Compute console, you will also be prompted to claim a certain amount of free resource plan. For more information, see Trial quota.

For Alibaba Cloud accounts registered before August 27, 2024, see the following steps to activate the service.

  1. Visit the Function Compute home page.

  2. Click Console to go to the service activation page, and click Activate Now to activate the service and enter the Function Compute console.

    Note
    • It is recommended that you activate the service using an Alibaba Cloud account and manage functions and other applications using RAM users. You can grant RAM users the permissions required for business according to the principle of least privilege. For more information, see Policy and examples.

  3. (Optional) When you log on to the Function Compute console for the first time, you need to click Alibaba Cloud Service Authorization in the pop-up Confirm dialog box to create a service-linked role to facilitate subsequent access to related Alibaba Cloud services using Function Compute.

    After the creation is successful, Function Compute can access your VPC, ECS, SLS, and Container Registry cloud resources. For more information about service-linked roles, see Service-linked roles.

Instructions

You can use the following methods to create web functions and deploy code.

  • Create in the Function Compute console: Suitable for building lightweight applications or quick verification scenarios, you can quickly create a single function.

  • Create using the Serverless Devs command line tool: Suitable for managing complex production projects and automated deployment scenarios, you can use YAML configuration files to manage multiple functions and related cloud resources. For more information, see Quick Start.

To simplify operations, this topic will detail the steps to create a function using the Function Compute console.

1. Develop and test the web application

Note

If you need to migrate an existing Flask application, you can skip this step and refer to Step 2: Generate a code package.

  1. Open a new command line window locally and run the following command to install the Flask and tabulate dependency libraries required by the application into the local environment:

    pip install Flask tabulate
  2. Create a folder named code and create a file named app.py in it. Paste the following sample code into the file. This code implements a simple calendar service and encapsulates it into an API interface. Users input year and month information (such as January 2025), and the API returns the corresponding calendar table.

    import calendar
    from flask import Flask, request
    from tabulate import tabulate
    import logging
    import json
    
    logger = logging.getLogger()
    app = Flask(__name__)
    
    
    @app.route("/", methods=["POST"])
    def get_month_calendar():
        # Obtain the request ID and print logs
        requestId = request.headers.get('x-fc-request-id', '')
        logger.info("FC Invoke Start RequestId: " + requestId)
        # Obtain the request content and check the request format
        data = json.loads(request.stream.read().decode('utf-8'))
        if not ('year' in data and 'month' in data):
            message = "Request must be in format such as {'year': '1999', 'month': '12'}"
            return message
    
        # Obtain the calendar table
        result = print_calendar(year=int(data['year']), month=int(data['month']))
        # Print logs before returning the result
        logger.info("FC Invoke End RequestId: " + requestId)
        return result
    
    
    def print_calendar(year, month):
        # Obtain the calendar matrix for the specified year and month
        cal = calendar.monthcalendar(year, month)
        # Replace dates not belonging to the month from 0 to an empty string
        cal = list(map(lambda sublist: list(map(lambda x: '' if x == 0 else x, sublist)), cal))
        # Create table headers
        headers = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
    
        # Use tabulate to print the calendar table
        return tabulate(cal, headers=headers, tablefmt="grid", stralign='center', numalign='center')
    
    
    if __name__ == "__main__":
        app.run(host='0.0.0.0', port=9000)
    
  3. Run the python3 app.py command to run the Flask application you created. When the output is Running on http://127.0.0.1:9000, it indicates that your Flask application has started successfully. You can then use the cURL command to test the application.

    python3 app.py 
     * Serving Flask app 'app'
     * Debug mode: off
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on http://127.0.0.1:9000
     * Running on http://47.100.XX.XX:9000
    Press CTRL+C to quit
  4. Open a new terminal window and use cURL to send a sample request. If successful, you will receive a calendar table.

    curl -X POST http://127.0.0.1:9000 -d '{"year": "2000", "month": "1"}'

    image

At this point, the local project creation and testing are complete.

2. Generate a code package

You will build a code package suitable for Function Compute locally. The code package needs to include the following contents:

  • Project files required by the web application.

  • If the dependency libraries required by the application are not in the runtime environment of the web function, the code package also needs to include these dependency libraries. For more information about the built-in dependency libraries of the web function runtime environment, see Built-in dependencies.

  1. Install dependencies: In the project root directory of the web application, run the following command to install the dependency libraries required by the application (in the example, tabulate) into the directory. After completion, the project root directory will contain project files and dependency libraries.

    Note

    The runtime environment of Python web functions already includes the Flask library, so installing tabulate can meet the needs of the sample application.

    pip install -t . tabulate
  2. Package all files in the project root directory.

    Linux or macOS

    In the project root directory, run zip code.zip -r ./*. This step packages the project files and dependency libraries into a ZIP file, completing the construction of the code package.

    Note

    Ensure you have read and write permissions on the directory.

    Windows

    Enter the project directory, select all files, right-click, and choose to package as a ZIP file. This step packages the project files and dependency libraries into a ZIP file, completing the construction of the code package.

3. Create a web function and deploy the code package

  1. Select the function type: Open the Function Compute 3.0 console. In the region list at the top left of the page, select the region where you want to create the function. It is recommended to choose a region close to you (such as East China 1-Hangzhou). Then, on the Function page, click Create Function. On the create function page, select Web Function.image

  2. Select the runtime environment: Follow the illustration to select Custom Runtime > Python > Python 3.10. This runtime has the dependency libraries required by the Flask framework built-in.image

    Note
    • For web functions, it is recommended to use Custom Runtime as the function runtime environment because Custom Runtime allows you to customize the startup command and listening port and supports single-instance multi-concurrency. The Built-in Runtime does not have these features and is more suitable for handling events generated by cloud products.

    • If you prefer containerized deployment, you can also use Custom Image to create a web function. This environment also supports single-instance multi-concurrency, but you need to manage the dependencies yourself.

    • For a detailed comparison of various runtime environments, see Function runtime environment selection.

  3. Deploy the code package: Follow the illustration to upload the ZIP format code package obtained in the previous step and configure the startup command as python3 app.py and the listening port as 9000. If you are migrating an existing Flask application, modify the configuration according to the actual startup command and port (for example, Flask's default port configuration is 5000).

    After completion, click Create and wait for the function creation to complete.image

4. Test the function

  1. Obtain the function URL: On the details page of the newly created function, click the Configuration tab, then in the left-side navigation pane, select Trigger. In the configuration information of the HTTP trigger, click the public access address to copy the address.

    image

  2. Test the function: You can use cURL, Postman, or any HTTP client to invoke the function and verify the functionality of the Flask application. For example, using cURL, execute the following sample command in the command line (replace the address with the address copied in the previous step).

    curl https://******.cn-hangzhou.fcapp.run -d '{"year": "2025", "month": "1"}' 

    The web interface will print the calendar information for January 2025. The sample output is as follows.

    image

    Note

    The sample command and output in this step are only applicable to the sample code. If you are migrating an existing application, invoke your service according to the actual interface name and parameters. For more information, see Test functions using cURL.

  3. (Optional) Access the function through a browser: The public access address provided by the HTTP trigger cannot be opened with a browser (forced download) and can only be used in a test environment. It is recommended that you bind the function to a custom domain name to support browser access and production environment use. For more information, see Configure a custom domain name.

5. (Optional) Clean up resources

Function Compute charges based on actual resource usage. Created function resources will not incur charges if not used. However, be aware of other cloud products or resources associated with the function resources you create, such as data stored in OSS and NAS, and created triggers.

If you want to delete a function, log on to the Function Compute console, click Function, select the region, and in the Operation column of the target function, select More > Delete. Then, in the pop-up dialog box, confirm that the function to be deleted has no bound resources such as triggers, and confirm the deletion again.

image

Advanced operations

Now that you have created a web application and deployed it to a web function, you can refer to the following advanced operations based on your needs.

  • Develop code through the console: Considering that you may want to migrate existing web applications to web functions, this topic introduces the process of local code development and code package generation. If you want to simplify the deployment process, you can also perform cloud development and real-time debugging through the WebIDE in the Function Compute console. This method does not require local code package generation and is suitable for rapid iteration development needs. For more information, see How to use WebIDE.

    Note

    WebIDE only supports Python, Node.js, and PHP languages. For other languages (such as Java, Go, etc.), only uploading compiled and packaged ZIP files or binary files is supported.

  • Continuously deploy projects through the application center: If you want to automatically build and deploy your code to Function Compute on the cloud to achieve CI/CD, it is recommended to use the application center. For more information, see Deploy existing Function Compute projects through the application center for continuous deployment.

  • Configure logs: To facilitate debugging, troubleshooting, or meeting security audit requirements, it is recommended to configure logs for functions. For detailed steps, see Configure logs.

References

For steps to add dependency packages for each language, see the following documents:

Python

Python deployment code package

Node.js

Node.js deployment code package

Java

Java compile and deploy code package

Go

Go compile and deploy code package

C#

C# compile and deploy code package

PHP

PHP deployment code package