Creating an Event Function Using a Container Image Built with Python
For details about how to use a container image to create and execute an event function, see Creating an Event Function Using a Container Image and Executing the Function. This section describes how to create an image using Python and verify the image locally.
Step 1: Creating an Image
Take the Linux x86 64-bit OS as an example. (There are no specific requirements for system configurations.)
- Run the following command to create an empty folder named custom_container_event_example:
mkdir custom_container_event_example && cd custom_container_event_example
- Use Python to implement an HTTP server to process init and invoke requests and send responses.
Run the following command to create a main.py file:
touch main.py
Introduce the Flask framework in the code and implement a function handler (method POST and path /invoke) and an initializer (method POST and path /init). Here is the code for main.py:import json from flask import Flask, request # Create a Flask application instance. app = Flask(__name__, template_folder='templates', static_folder='static') # Define the initialization API. @app.route('/init', methods=['POST']) def init(): # Print the request path for debugging. print("***" + request.path + "***", flush=True) # Build response data. data = { "statusCode": 200, "isBase64Encoded": False, "body": json.dumps("init successes"), "headers": { "Content-Type": "application/json" } } return json.dumps(data) # Define the API. @app.route('/invoke', methods=['POST']) def invoke(): print("***" + request.path + "***", flush=True) data = { "statusCode": 200, "isBase64Encoded": False, "body": json.dumps("invoke successes"), "headers": { "Content-Type": "application/json" } } return json.dumps(data) # Main program entry if __name__ == '__main__': app.run(host="0.0.0.0", port=8000) - Create a Dockerfile.
touch Dockerfile
The content of Dockerfile is as follows:FROM ubuntu:22.04 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} RUN apt-get update && \ apt-get install -y --no-install-recommends python3 pip && \ apt-get clean RUN pip3 install --verbose flask jsons requests --no-cache-dir COPY main.py ${HOME} RUN chown -R ${USER_ID}:${GROUP_ID} ${HOME} RUN chmod -R 775 ${HOME} USER ${USER_NAME} WORKDIR ${HOME} EXPOSE 8000 ENTRYPOINT ["python3", "main.py"]
Table 1 Instructions Instruction
Description
FROM
Specifies base image ubuntu:22.04. The base image is mandatory and its value can be changed.
ENV
Sets environment variables HOME (/home/custom_container), GROUP_NAME and USER_NAME (custom_container), and USER_ID and GROUP_ID (1003). These environment variables are mandatory and their values can be changed.
RUN
Executes commands. The format is RUN <command>. For example, RUN mkdir -m 550 ${HOME} means to create directory ${HOME} for user ${USER_NAME} during container building.
COPY
Copies files or directories from the build context to the image. Copy main.py to the ${HOME} directory of user ${USER_NAME} in the container.
USER
Switches to user ${USER_NAME}.
WORKDIR
Switches the working directory to the ${HOME} directory of user ${USER_NAME}.
EXPOSE
Informs Docker that the container listens on the specified network ports at runtime. Expose port 8000 of the container and do not change it.
ENTRYPOINT
Sets the executable command that is run each time a container starts. Run the python3 main.py command to start a container.
- Run the following command to build an image:
docker build -t custom_container_event_example:latest .
In the preceding command, the image name is custom_container_event_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.
Step 2: Performing Local Verification
- Run the following command to start the Docker container:
docker run -u 1003:1003 -p 8000:8000 custom_container_event_example:latest
- Open a new Command Prompt, and send a message through port 8000 to access the /init directory specified in the template code.
curl -XPOST -H 'Content-Type: application/json' localhost:8000/init
The following information is returned based on the module code:
{ "statusCode": 200, "isBase64Encoded": False, "body": json.dumps("init successes"), "headers": { "Content-Type": "application/json" } } - Open a new Command Prompt, and send a message through port 8000 to access the /invoke directory specified in the template code.
curl -XPOST -H 'Content-Type: application/json' -d '{"message":"HelloWorld"}' localhost:8000/invokeThe following information is returned based on the module code:
{ "statusCode": 200, "isBase64Encoded": False, "body": json.dumps("invoke successes"), "headers": { "Content-Type": "application/json" } }
Step 3: Creating a Function
Once you build the container image locally, you can create a function on the console.
For details, see Creating an Event Function Using a Container Image and Executing the Function. Start from Step 3: Upload the Image.
Helpful Links
- For more information about function development, such as the supported runtimes, trigger events, function project packaging specifications, and DLL referencing, see Function Development Overview.
- For details about the syntax and SDK APIs of function development in Python, see Function Development Overview.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot