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 are no requests, the system automatically destroys instances, and you only pay for the resources actually consumed.
Overview
This topic describes how to deploy a Flask application using the web function in Function Compute. The overall process is as follows:
Develop and test the application: (If you are migrating an existing application, you can skip this step.) Use the sample code to create a project locally, edit and test the API code to ensure your APIs function properly.
Generate the 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.
Upload and deploy the code package: Configure the function parameters, and then upload the ZIP file to Fuction Compute. This completes the creation of the web function.
Test the function: Call the function to check whether the Flask application is running properly.
Prerequisites
Procedure
You can use the following methods to deploy your code and create a web function.
Create using the Function Compute console: Single-function creation, suitable for building lightweight applications or rapid verification scenarios
Create using the Serverless Devs command line tool: Suitable for managing complex production projects and automated deployment scenarios, allowing you to manage multiple functions and related cloud resources by using YAML configuration files. For more information, see Quick start.
This topic will walk you through the steps to create a function using the Function Compute console.
1. Develop and test the application
If you're migrating an existing Flask application, you can skip this step and refer to Generate the code package.
Open a new command line window locally and run the following command to install the
Flask
andtabulate
dependency libraries required by the application into the local environment:pip install Flask tabulate
Create a folder named
code
and create a file namedapp.py
in it. Paste the following sample code into the file. This code implements a simple calendar service and encapsulates it into an API. 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 specified 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)
Run the
python3 app.py
command to start the Flask application you created. When you see the outputRunning on http://127.0.0.1:9000
, it means your Flask application has started successfully. You can now 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
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"}'
At this stage, local project creation and testing are complete.
2. Generate the code package
In this step, you are going to build a code package locally for deployment to Function Compute. The code package needs to include the following contents:
Project files required by the Flask application.
If your application requires dependency libraries that are not included in Function Compute's built-in list, you must package those dependencies with your code. For details about built-in dependencies in web function runtimes, see Built-in dependencies.
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
).NotePython runtimes of Function Compute environment already include the
Flask
library, so installingtabulate
alone can meet the needs of the sample application.pip install -t . tabulate
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.NoteMake sure 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. Upload and deploy the code package to create the web function
Select the function type: Go to the Function Compute 3.0 console. In the left-side navigation pane, click Functions. In the top navigation bar, select a region (one that is close to you). Then, click Create Function. On the Create Function page, select Web Function.
Select the runtime: Follow the illustration to select
. This runtime has the dependency libraries required by the Flask framework built-in.NoteFor web functions, we recommend that you use a Custom Runtime because this type of runtime allows you to customize the startup command and listening port and supports concurrent request handling. A Built-in Runtime does not have these features and is more suitable for handling events generated by other Alibaba Cloud services.
If you prefer containerized deployment, you can also use a Custom Container runtime to create your web function. This type of runtime also supports concurrent request processing, but you need to manage the dependencies yourself.
For a detailed comparison of various runtimes, see Function runtime selection.
Deploy the code package: Follow the illustration to upload the ZIP package generated in the previous step and configure the startup command as
python3 app.py
and the listening port as9000
. If you are migrating an existing Flask application, modify the configuration as needed (for example, Flask's default port configuration is 5000).Then, click Create and wait for the function creation to complete.
4. Test the function
Obtain the function URL: On the Function Details page of the newly created function, click the Triggers tab. In the configuration information of the HTTP trigger, copy the public endpoint by clicking it.
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 URL with the function URL 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. A sample output is as follows:
NoteThe sample command and output in this step are only applicable to the sample code. If you have migrated an existing application, invoke it according to the actual interface name and parameters. For more information, see Test functions using cURL.
(Optional) Enable browser access: The HTTP trigger's public endpoint is for testing only and will cause forced downloads if opened in a browser. We recommend that you bind your function to a custom domain name for browser and production use. For more information, see Configure custom domain names.
5. (Optional) Release resources
Function Compute charges based on actual resource usage. Created function resources will not incur charges if not used. However, be aware of other services or resources associated with the function you create, such as data stored in Object Storage Service (OSS) buckets or File Storage NAS (NAS), and created triggers.
If you want to delete a function, log on to the Function Compute console, click Functions, select the region, and in the Actions column of the target function, select from the kebab menu. 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.
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 if you want.
Develop code through the console: Considering that you may want to migrate existing web applications to web functions, this topic introduced 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. For more information, see How to use WebIDE.
NoteWebIDE only supports Python, Node.js, and PHP. For other languages (such as Java, Go, etc.), you still need to upload compiled and packaged ZIP files or binary files.
Continuously deploy projects through Serverless Application Center: To automatically build and deploy your code to Function Compute to achieve CI/CD, see Use Serverless Application Center to implement CI/CD on existing Function Compute projects.
Configure logs: We recommend that you configure logs for your functions to facilitate debugging, troubleshooting, or meeting security audit requirements. For detailed steps, see Configure the logging feature.
References
For steps to add dependencies for each language, see the following documents: