Build a high-availability WeChat Mini Program service
This topic describes how to build a highly available backend service for a WeChat Mini Program on ECS instances running the Alibaba Cloud Linux 3 operating system. You will also develop a simple WeChat Mini Program named ECS Assistant. The Mini Program remotely calls the backend service deployed on ECS instances, allowing you to query instance details by entering an instance ID.
Step 1: Prepare the environment and resources
To deploy a highly available Mini Program service, you need two ECS instances running Alibaba Cloud Linux 3.2104 LTS 64-bit and one CLB instance. For more information, see Overview of instance creation methods and Create and manage CLB instances.
This tutorial uses the following configurations:
ECS
Region: China (Beijing)
Operating system: Alibaba Cloud Linux 3.2104 LTS 64-bit
Instance type: 1 vCPU, 2 GiB of memory
Number of instances: 2 (ECS01 and ECS02)
Other parameters: Use the default values, or customize them as needed.
CLB
Region and zone: Select the same region as the ECS instances.
Instance type: Select an instance type based on your business requirements.
Billing method: pay-as-you-go
Instance type: Internet-facing
Number of instances: 1
IP version: IPv4
Step 2: Configure resources and build the service
One-click
ROS
After preparing the resources, you can use the one-click configuration feature to quickly configure resources or build applications. This feature is based on Resource Orchestration Service (ROS), which helps developers automate resource configuration using Infrastructure as Code (IaC). To view specific configuration details such as software versions and installation commands, see the Manual configuration section of this topic. The template automates the following tasks:
Configure a security group for the ECS instances.
Create a role and attach it to the ECS instances.
Install and configure Nginx.
Install and configure the uWSGI server.
Install Python and deploy the backend service code.
Procedure
Click the one-click configuration template link to go to the ROS console. Click Previous: Select Template. The Template Content section displays the details of the YAML file.
The ROS console defaults to your last-accessed region. Switch to the region where your resources are located. For example, select the China (Beijing) region. Retain the default values for other parameters and click Next: Configure Parameters.
On the Configure Parameters page, modify the stack name, select the ECS instances that you created, specify a name for the ECS instance RAM role, and select the created CLB instance (formerly an SLB instance). After filling in and confirming all required information, click Next: Review and Confirm.
Confirm that all the configuration information is correct and click Create.
On the Stack Information tab, in the Basic Information section, check the Status. A status of CreateSucceeded indicates that the configuration is complete.

Terraform
Terraform is an Infrastructure as Code (IaC) tool that helps developers and operations teams automate the creation, deployment, and management of infrastructure. Instead of manual setup, you can use code to define and configure cloud infrastructure.
Procedure
Click Run in Terraform to open Terraform Explorer. The following Terraform code is automatically loaded.
provider "alicloud" { region = var.region } variable "region" { description = "Region where resources will be created" default = "cn-beijing" } variable "common_name" { default = "deploy-java-web-by-terraform" description = "Common name for resources" } variable "system_disk_category" { default = "cloud_essd" description = "The category of the system disk." } variable "instance_password" { default = "Test@123456" description = "Server login password" } variable "image_id" { default = "aliyun_3_x64_20G_alibase_20240528.vhd" description = "Please choose the Alibaba Cloud Linux 3 Image ID for the instance" } variable "instance_type" { description = "Instance type" default = "ecs.e-c1m2.large" } variable "instance_count" { description = "The number of ECS instances to create." default = "2" } variable "ecs_ram_role_name" { description = "English letters, numbers, or ' - ' are allowed. The number of characters should be less than or equal to 64." default = "EcsRoleForMiniProgramServer" } data "alicloud_zones" "default" { available_disk_category = var.system_disk_category available_resource_creation = "VSwitch" available_instance_type = var.instance_type } resource "alicloud_ram_role" "role" { name = var.ecs_ram_role_name document = <<EOF { "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" } EOF description = "Ecs ram role." force = true } resource "alicloud_ram_policy" "policy" { policy_name = "${var.ecs_ram_role_name}Policy" policy_document = <<EOF { "Statement": [ { "Action": [ "ecs:DescribeInstances", "ecs:DescribeInstanceStatus" ], "Effect": "Allow", "Resource": ["*"] } ], "Version": "1" } EOF description = "this is a policy test" force = true } resource "alicloud_ram_role_policy_attachment" "attach" { policy_name = alicloud_ram_policy.policy.policy_name policy_type = "Custom" role_name = alicloud_ram_role.role.name } resource "alicloud_vpc" "vpc" { vpc_name = "${var.common_name}-vpc" cidr_block = "192.168.0.0/16" } resource "alicloud_vswitch" "vswitch" { vpc_id = alicloud_vpc.vpc.id vswitch_name = "${var.common_name}-vsw" cidr_block = "192.168.0.0/24" zone_id = data.alicloud_zones.default.zones.0.id } resource "alicloud_security_group" "sg" { security_group_name = "${var.common_name}-sg" vpc_id = alicloud_vpc.vpc.id description = "Security group for ECS instance" } resource "alicloud_security_group_rule" "allow_ssh" { type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "22/22" priority = 1 security_group_id = alicloud_security_group.sg.id cidr_ip = "0.0.0.0/0" } resource "alicloud_security_group_rule" "allow_80" { type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "80/80" priority = 1 security_group_id = alicloud_security_group.sg.id cidr_ip = "0.0.0.0/0" } resource "alicloud_ram_role_attachment" "attach" { role_name = alicloud_ram_role.role.name instance_ids = alicloud_instance.ecs_instance.*.id } resource "alicloud_instance" "ecs_instance" { count = var.instance_count instance_name = "${var.common_name}-ecs" image_id = var.image_id instance_type = var.instance_type security_groups = alicloud_security_group.sg.*.id vswitch_id = alicloud_vswitch.vswitch.id password = var.instance_password internet_max_bandwidth_out = 100 system_disk_category = var.system_disk_category } resource "alicloud_eip_address" "eip" { description = "${var.common_name}-eip" address_name = "${var.common_name}-eip" netmode = "public" bandwidth = "5" } resource "alicloud_eip_association" "clb_ip" { allocation_id = alicloud_eip_address.eip.id instance_id = alicloud_slb_load_balancer.instance.id } resource "alicloud_slb_load_balancer" "instance" { load_balancer_name = "${var.common_name}-clb" load_balancer_spec = "slb.s2.small" internet_charge_type = "PayByTraffic" address_type = "intranet" vswitch_id = alicloud_vswitch.vswitch.id } resource "alicloud_slb_listener" "listener" { load_balancer_id = alicloud_slb_load_balancer.instance.id backend_port = 80 frontend_port = 80 protocol = "http" bandwidth = -1 health_check = "on" health_check_uri = "/" health_check_connect_port = 80 healthy_threshold = 3 unhealthy_threshold = 3 health_check_timeout = 5 health_check_interval = 2 health_check_http_code = "http_2xx,http_3xx" } resource "alicloud_slb_attachment" "default" { load_balancer_id = alicloud_slb_load_balancer.instance.id instance_ids = alicloud_instance.ecs_instance.*.id weight = 80 } resource "alicloud_ecs_command" "deploy" { name = "DeployMiniProgramServer" type = "RunShellScript" command_content = base64encode(local.command_content) timeout = 3600 working_dir = "/root" } resource "alicloud_ecs_invocation" "invocation" { instance_id = alicloud_instance.ecs_instance.*.id command_id = alicloud_ecs_command.deploy.id timeouts { create = "10m" } } locals { command_content = <<EOF #!/bin/bash if [ ! -f .tf.provision ]; then # Build a Mini Program echo "Name: Build a Mini Program" > .tf.provision fi name=$(grep "^Name:" .tf.provision | awk -F':' '{print $2}' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') if [ "$name" != "Build a Mini Program" ]; then echo "The one-click configuration for the \"$name\" tutorial has already been used on this instance. You cannot use the one-click configuration of this tutorial again." exit 0 fi if ! grep -q "^Step1: Install Python$" .tf.provision; then echo "#########################" echo "# Install Python" echo "#########################" mkdir /data && touch /data/GetServerInfo.py cat > /data/GetServerInfo.py << EOF2 # -*- coding: utf-8 -*- from flask import Flask, jsonify, request from alibabacloud_credentials.client import Client as CredClient from alibabacloud_credentials.models import Config as CredConfig from alibabacloud_ecs20140526 import models as ecs_20140526_models from alibabacloud_ecs20140526.client import Client as EcsClient from alibabacloud_tea_openapi.models import Config app = Flask(__name__) ecs_ram_role = '${var.ecs_ram_role_name}' region = '${var.region}' # For health checks. @app.route('/', methods=['HEAD', 'GET']) def index(): return "ok" # Declare the URL and request method of the response in the app.route decorator. @app.route('/ecs/getServerInfo', methods=['GET']) def get_server_info(): cred_config = CredConfig( type='ecs_ram_role', role_name=ecs_ram_role, ) cred_client = CredClient(cred_config) ecs_config = Config(credential=cred_client, region_id=region) ecs_client = EcsClient(ecs_config) # Obtain request parameters by using the GET method. instance_id = request.args.get("instanceId") if instance_id is None: return "Invalid Parameter" instance_ids = [instance_id] # Query instance information. describe_instances_request = ecs_20140526_models.DescribeInstancesRequest() describe_instances_request.region_id = region describe_instances_request.instance_ids = str(instance_ids) describe_instances_response = ecs_client.describe_instances(describe_instances_request) # The returned data is in bytes. You need to convert the data to a string and then deserialize the string into a JSON object. if len(describe_instances_response.to_map()['body']['Instances']['Instance']) == 0: return jsonify({}) instance_info = describe_instances_response.to_map()['body']['Instances']['Instance'][0] # Query the instance status. describe_instance_status_request = ecs_20140526_models.DescribeInstanceStatusRequest() describe_instance_status_request.region_id = region describe_instance_status_request.instance_id = instance_ids describe_instance_status_response = ecs_client.describe_instance_status(describe_instance_status_request) instance_status = describe_instance_status_response.to_map()['body']['InstanceStatuses']['InstanceStatus'][0][ 'Status'] # Encapsulate the result. result = { # The number of vCPUs. 'Cpu': instance_info['Cpu'], # The memory size. 'Memory': instance_info['Memory'], # The name of the operating system. 'OSName': instance_info['OSName'], # The instance type. 'InstanceType': instance_info['InstanceType'], # The public IP address of the instance. 'IpAddress': instance_info['PublicIpAddress']['IpAddress'][0], # The maximum public outbound bandwidth. 'InternetMaxBandwidthOut': instance_info['InternetMaxBandwidthOut'], # The instance status. 'instance_status': instance_status } return jsonify(result) if __name__ == "__main__": app.run() EOF2 touch /data/requirements.txt cat > /data/requirements.txt << EOF2 wheel alibabacloud_ecs20140526 Flask==2.0.3 EOF2 pip3 install --upgrade pip && pip3 install -r /data/requirements.txt echo "Step1: Install Python" >> .tf.provision else echo "#########################" echo "# Python has been installed" echo "#########################" fi if ! grep -q "^Step2: Install uWSGI Server$" .tf.provision; then echo "#########################" echo "# Install uWSGI Server" echo "#########################" pip3 install uwsgi touch /data/uwsgi.ini cat > /data/uwsgi.ini << EOF2 [uwsgi] # The address and port that are used when uWSGI starts. socket=127.0.0.1:5000 # The website directory. chdir=/data # The Python startup file. wsgi-file=GetServerInfo.py # The application variable name that is used to start the Python program. callable=app # The number of processors. processes=1 # The number of threads. threads=2 # The status check address. stats=127.0.0.1:9191 # The process ID (PID) file of the main process after startup. pidfile=/data/uwsgi.pid # Run uWSGI in the background and save log information to uwsgi.log. daemonize=/data/uwsgi.log EOF2 uwsgi /data/uwsgi.ini echo "Step2: Install uWSGI Server" >> .tf.provision else echo "#########################" echo "# uWSGI Server has been installed" echo "#########################" fi if ! grep -q "^Step3: Install Nginx$" .tf.provision; then echo "#########################" echo "# Install Nginx" echo "#########################" yum install -y nginx touch /etc/nginx/conf.d/app.conf cat > /etc/nginx/conf.d/app.conf << EOF2 server { listen 80 default_server; server_name app.example.com; root /var/www/html; # Add index.php to the list if you are using PHP. index index.html index.htm index.nginx-debian.html; location / { # The forwarding address. uwsgi_pass 127.0.0.1:5000; include uwsgi_params; } } EOF2 systemctl start nginx echo "Step3: Install Nginx" >> .tf.provision else echo "#########################" echo "# Nginx has been installed" echo "#########################" fi EOF } output "public_ip" { value = alicloud_eip_address.eip.ip_address }Modify the parameters as needed. By default, one VPC instance, two pay-as-you-go ECS instances running Alibaba Cloud Linux 3, one pay-as-you-go CLB instance, one pay-as-you-go EIP instance, and one RAM role will be created in cn-beijing. For billing information about each instance, see the following documents:
For information about ECS billing, see Billing overview.
For information about CLB billing, see Billing overview.
For information about EIP billing, see Billing overview.
Click Start Debugging to preview the details of the resources to be created. If the resource information is correct, click Preview and Run to start creating the resources. When the task execution status shows that the execution is successful, the deployment is complete.
Verify the deployment. In your browser, enter the following URL. Replace <clb_public_ip> with the IP address returned by Terraform.
http://<clb_public_ip>/ecs/getServerInfoIf the command returns
Invalid Parameter, the service deployment is successful.
Manual
You can manually configure the ECS and CLB instances by performing the following steps:
Step 1: Create and attach a RAM role
After the instances are created, you must create a RAM role and attach the role to the ECS instances. The backend service uses the role to call the SDK.
This allows the instances to use temporary credentials from Security Token Service (STS) to access Alibaba Cloud APIs. The temporary credentials are automatically updated on a regular basis. This approach protects your account's AccessKey pair and allows you to use RAM for fine-grained access control and permission management.
Create an instance RAM role.
Log on to the RAM console as a RAM administrator.
In the left-side navigation pane, choose .
On the Roles page, click Create Role.

On the Create Role page, select Alibaba Cloud Service for Select Trusted Entity, select a specific Alibaba Cloud service, and then click OK.
NoteThe available services for Trusted Service are listed in the console.
(Optional) To trust access from a different account or from multiple Alibaba Cloud services, click Switch to Editor to specify the Alibaba Cloud services.
The editor supports the visual editor and script editor. You can use either of the editors. The following example shows how to allow the ActionTrail service of another Alibaba Cloud account (Account ID = 177*******6878) to assume the RAM role that you are creating and perform operations in the current Alibaba Cloud account.
Visual editor
Specify the name of the Alibaba Cloud service in the Principal field.


Script editor
In the
Servicefield of thePrincipal, specify the Alibaba Cloud service.{ "Version": "1", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "177*******6878@actiontrail.aliyuncs.com" }, "Action": "sts:AssumeRole" } ] }
In the Create Role dialog box, enter a RAM Role Name and click OK.
Attach the RAM role to the instances.
Go to ECS console - Instances.
In the top navigation bar, select the region and resource group of the resource that you want to manage.
Click the ID of the target instance to go to its details page. Click More to expand all operations, and then search for and click Grant/Revoke RAM Role.
In the dialog box that appears, select the instance RAM role that you created and click OK.
Step 2: Log on to the ECS instances
After you activate a free trial ECS server, the system creates an ECS instance. Before you use the ECS instance to deploy applications or set up an environment, you must set a password for the instance before you can log on to the instance.
Go to ECS console - Instances.
In the top navigation bar, select the region of the ECS instance.
Set the logon password for the ECS instance.
Click the ID of the target instance to go to its details page. Click More to expand all operations, and then search for and click Reset Instance Password.
ImportantYou can reset the instance password about 3 to 5 minutes after the instance is created. If you cannot reset the password, wait and try again.
(Optional) In the dialog box that appears, click Restart Now to apply the password.
If you select Reset Password Online for How to Reset Password, skip this step.
Click the ID of the trial instance, select the Security Groups tab, click Manage Rules in the Actions column of the security group, and then add security group rules to allow access to SSH (port 22) and HTTP (port 80).

Remotely connect to the ECS instance.
Return to the Instances page and click Connect in the Actions column of the instance.
In the Connect and Command dialog box, click Log on now next to Connect via Workbench.
In the Log In to Instance dialog box, enter your logon information.
Repeat the preceding steps to log on to the ECS02 instance.
Step 3: Install Nginx
Run the command to install Nginx.
sudo yum update && sudo yum -y install nginxStart Nginx.
sudo systemctl start nginxRun the following command to check the running status of the Nginx service:
If
Active: active (running)is returned, Nginx is started.systemctl status nginxRepeat the preceding steps to install Nginx on the ECS02 instance.
Step 4: Develop the backend service
Create a service directory.
sudo mkdir /data && cd /dataCreate and edit the dependency file for the Python service.
sudo vim requirements.txtAfter entering the Vim editor, press the
ikey to enter edit mode and paste the following content.wheel alibabacloud_credentials alibabacloud_ecs20140526 Flask==2.0.3After pasting, press the Esc key, and enter
:xto save the changes and exit.Run the following command to install the dependencies:
sudo pip3 install --upgrade pip && sudo pip3 install -r requirements.txtCreate and edit the code file for the Python service.
sudo vim get_server_info.pyAfter entering the Vim editor, press the
ikey to enter edit mode and paste the following content.NoteIn the code, the value of
ecs_ram_rolemust be the name of the RAM role that you created.In the code, the value of
regionmust be the same as the region in which you created the instances.# -*- coding: utf-8 -*- import json from flask import Flask, jsonify, request from alibabacloud_credentials.client import Client as CredClient from alibabacloud_credentials.models import Config as CredConfig from alibabacloud_ecs20140526 import models as ecs_20140526_models from alibabacloud_ecs20140526.client import Client as EcsClient from alibabacloud_tea_openapi.models import Config app = Flask(__name__) # The name of the RAM role that is attached to the ECS instance. ecs_ram_role = 'EcsRamRoleTest' # The region where the ECS instance is located. region = 'cn-beijing' # For health checks. @app.route('/', methods=['HEAD', 'GET']) def index(): return "ok" # Declare the URL and request method in the app.route decorator. @app.route('/ecs/getServerInfo', methods=['GET']) def get_server_info(): cred_config = CredConfig( type='ecs_ram_role', role_name=ecs_ram_role, ) cred_client = CredClient(cred_config) ecs_config = Config(credential=cred_client, region_id=region) ecs_client = EcsClient(ecs_config) # Obtain request parameters by using the GET method. instance_id = request.args.get("instanceId") if instance_id is None: return "Invalid Parameter" instance_ids = [instance_id] # Query instance information. describe_instances_request = ecs_20140526_models.DescribeInstancesRequest( region_id=region, instance_ids=json.dumps(instance_ids) ) describe_instances_response = ecs_client.describe_instances(describe_instances_request) if len(describe_instances_response.body.instances.instance) == 0: return jsonify({}) instance_info = describe_instances_response.body.instances.instance[0] # Query the instance status. describe_instance_status_request = ecs_20140526_models.DescribeInstanceStatusRequest( region_id=region, instance_id=instance_ids ) describe_instance_status_response = ecs_client.describe_instance_status(describe_instance_status_request) instance_status = describe_instance_status_response.body.instance_statuses.instance_status[0].status # Encapsulate the result. result = { # The number of vCPUs. 'Cpu': instance_info.cpu, # The memory size. 'Memory': instance_info.memory, # The name of the operating system. 'OSName': instance_info.osname, # The instance type. 'InstanceType': instance_info.instance_type, # The public IP address of the instance. 'IpAddress': instance_info.public_ip_address.ip_address[0], # The maximum public outbound bandwidth. 'InternetMaxBandwidthOut': instance_info.internet_max_bandwidth_out, # The instance status. 'instance_status': instance_status } return jsonify(result) if __name__ == "__main__": app.run()After pasting, press the Esc key, and enter
:xto save and exit.Repeat the preceding steps to develop the backend service on the ECS02 instance.
Step 5: Install uWSGI Server
After you write the backend code, you must install and use uWSGI to start the Flask service.
Run the command to install uWSGI.
sudo pip3 install uwsgiCreate a uWSGI configuration file.
cd /data && sudo vim uwsgi.iniIn the Vim editor, press the
ikey to enter the insert mode.[uwsgi] # The address and port that are used when uWSGI starts. socket=127.0.0.1:5000 # The website directory. chdir=/data # The Python startup file. wsgi-file=get_server_info.py # The application variable name that is used to start the Python program. callable=app # The number of processors. processes=1 # The number of threads. threads=2 # The status check address. stats=127.0.0.1:9191 # The PID file of the main process after startup. pidfile=uwsgi.pid # Run uWSGI in the background and save log information to uwsgi.log. daemonize=uwsgi.logAfter pasting the content, press the Esc key, enter
:x, and then press the Enter key to save the file and exit the editor.Run the
which uwsgicommand to find and confirm the full path of theuwsgiexecutable file.The following information is returned:
/usr/local/bin/uwsgiStart the uWSGI server.
sudo /usr/local/bin/uwsgi uwsgi.iniRun the following command to check the startup status of the uWSGI service. If a result similar to the one shown in the following figure is returned, the service is started.
ps aux | grep uwsgi
Repeat the preceding steps to install uWSGI Server on the ECS02 instance.
Step 6: Configure and restart Nginx
After you start the backend service, you must add an Nginx configuration to proxy the backend service.
Create a configuration file.
sudo vim /etc/nginx/conf.d/app.confIn the Vim editor, press the
ikey to enter the insert mode.server { listen 80 default_server; server_name app.example.com; root /var/www/html; # Add index.php to the list if you are using PHP. index index.html index.htm index.nginx-debian.html; location / { # The forwarding address. uwsgi_pass 127.0.0.1:5000; include uwsgi_params; } }After pasting the content, press the Esc key, enter
:x, and then press the Enter key to save the file and exit the editor.Restart Nginx.
sudo nginx -s reloadVerify that the configuration is successful.
NoteIf the service fails to start, check the /data/uwsgi.log file for the cause.
curl http://127.0.0.1/ecs/getServerInfoIf
Invalid Parameteris returned, the configuration is successful.Repeat the preceding steps to configure and restart Nginx on the ECS02 instance.
Step 7: Configure a listener
A CLB listener checks for connection requests and forwards them to backend servers based on configured rules.
Log on to the CLB console.
On the Instances page, click the ID of the created CLB instance.
On the Listeners tab, click Add Listener.
In the Protocol & Listener step of the configuration wizard, configure the following parameters, retain the default settings for other parameters, and then click Next.
Parameter
Description
Example
Select listener protocol
The protocol that is used by the listener.
HTTP
Listener port
The frontend port that is used to receive requests and forward requests to backend servers.
Valid values: 1 to 65535.
80
Listener name
A custom name for the listener.
HTTP_80
In the Backend Servers step of the configuration wizard, select Default Server Group. You can view the added ECS01 and ECS02 instances. If they are not added by default, click Add More and select the ECS01 and ECS02 instances that you created.
Enter the ports for ECS01 and ECS02. In this tutorial, set the ports to 80 for both instances and click Next.
In the Health Check step of the configuration wizard, retain the default settings, click Next, and then click Submit. After you submit the configurations, click OK to complete the listener configuration.
Step 3: Register a WeChat Mini Program
Before you develop a Mini Program, you must register an account for the Mini Program.
Go to the Mini Program page, click Register, and follow the on-screen instructions to enter the required information and submit the required materials to complete the account application.

Log on to the Mini Program admin console with your WeChat Official Accounts Platform account. Choose Development > Development Settings to view the AppID of the Mini Program. Record the AppID for later use.

Step 4: Set up the project
After starting the backend service, you can develop the Mini Program. First, install the development environment for the Mini Program.
Go to the Node.js page to download and install the Node.js development environment.
Download and install WeChat DevTools. For more information, see Download DevTools.
Open WeChat DevTools and use WeChat to scan the QR code to log on.
Click the plus sign (+) to create a sample WeChat Mini Program project.

Specify the project information and click Create.
Project Name: Enter a project name. Example: ECSAssistant.
Directory: Specify a directory. Example: D:\workspace\wechat\ECSAssistant.
AppID: The unique identifier of the Mini Program. You can obtain the AppID from the Mini Program console.
Development Mode: Select Mini Program.
Backend Service: Select Do not use cloud services.

Configure the project to allow access to non-HTTPS domain names. In the top menu bar, choose Settings > Project settings. On the Local Settings tab, select Do not verify valid domain names, web-view (business domain names), TLS versions, and HTTPS certificates.
Step 5: Develop the Mini Program
After installing the development environment, write the code for the Mini Program.
The following figure shows the structure of the sample project.
The project structure contains three files that are prefixed with
app. The files define the global configurations of the Mini Program.app.json: the application configuration file. This file is used to configure the page list, default window title, and navigation bar background color of the Mini Program. For more information, see Global Configuration.app.acss: the application style file. This file defines the global styles that apply to all pages of the Mini Program.app.js: the application logic file. This file can be used to configure the lifecycle of the Mini Program, declare global data, and call APIs.
All page files of the Mini Program are stored in the
pages/directory. A page file can be one of the following types:.js,.wxml,.wxss, and.json. A page configuration file takes effect only on the current page. The.wxmlfile defines the structure of the current page. All pages in the Mini Program must be declared in theapp.jsonfile. For more information, see Code Structure.The top-level directory of the project also contains the project.config.json development tool configuration file and the sitemap.json crawler index file.
ECSAssistant ├── app.js ├── app.json ├── app.wxss ├── pages │ ├── index │ │ ├── index.js │ │ ├── index.json │ │ ├── index.wxml │ │ └── index.wxss │ └── logs │ ├── logs.js │ ├── logs.json │ ├── logs.wxml │ └── logs.wxss ├── project.config.json └── sitemap.jsonEdit the
app.jsonfile to change the page title of the Mini Program to ECS Assistant. The following code provides the modified content of theapp.jsonfile.{ "pages":[ "pages/index/index", "pages/logs/logs" ], "window":{ "backgroundTextStyle":"light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "ECS Assistant", "navigationBarTextStyle":"black" }, "style": "v2", "sitemapLocation": "sitemap.json" }Edit the
pages/index/index.wxssfile to define the style of the index page. The following code provides the modified content of theindex.wxssfile..search-input { position: relative; margin-bottom: 50rpx; padding-left:80rpx; line-height: 70rpx; height: 80rpx; box-sizing: border-box; border: 2px solid #ff8f0e; border-radius: 100rpx; overflow: hidden; text-overflow: ellipsis; transition: border 0.2s; } .resultView { margin-top: 70rpx; } .result { position: relative; left: 30rpx; display: list-item; font-size: small; }Edit the
pages/index/index.jsfile to define the blur event for the search box. The following code provides the modified content of theindex.jsfile.NoteReplace <CLB_PUBLIC_IP> in your code with the public IP address of the CLB instance you just created.
Page({ data: { queryResult: null, showView: 'false', }, bindblur: function(e) { let that = this; wx.request({ url: 'http://<CLB_PUBLIC_IP>/ecs/getServerInfo', method: 'GET', data: { instanceId: e.detail.value }, success(res) { if(res.statusCode == 200){ that.setData({ queryResult: res.data, showView: !that.data.showView, }); }else{ that.setData({ showView: 'false', }); wx.showToast({ title: 'Enter your ECS instance ID', duration: 1500, icon: 'none', mask: true }) } } }) } })Edit the
pages/index/index.wxmlfile to create the display interface. The following code provides the modified content of theindex.wxmlfile.<view class='container'> <input placeholder='Enter your ECS instance ID' class='search-input' value='{{ inputValue }}' bindblur='bindblur'></input> <view class='resultView' hidden='{{ showView }}'> <text class='result'>CPU cores: {{queryResult.Cpu}}</text> <text class='result'>Memory size: {{queryResult.Memory}} MB</text> <text class='result'>Operating system: {{queryResult.OSName}}</text> <text class='result'>Instance type: {{queryResult.InstanceType}}</text> <text class='result'>Public IP address: {{queryResult.IpAddress}}</text> <text class='result'>Network bandwidth: {{queryResult.InternetMaxBandwidthOut}} MB/s</text> <text class='result'>Status: {{queryResult.instanceStatus == 'Running' ? 'Running':'Stopped'}}</text> </view> </view>After saving the file, the editor automatically refreshes. If the following interface appears, the Mini Program is running.

Step 6: Test the WeChat Mini Program
After you complete the preceding steps, you have deployed the backend program and developed the Mini Program on your local machine.
You can log on to the ECS console, copy the ID of the ECS instance that you created, and then enter the ID into the input box of the Mini Program to view the result.
To verify the service's high availability, simulate a failure by stopping one of the ECS instances:
Log on to the ECS console, find the target instance, click
in the Actions column, and then click Stop in the panel that appears.After the instance status changes to Stopped, query the ECS instance ID in the Mini Program again. If you still receive the instance details, the high availability setup is working.
The following figure shows the user interface (UI) of the Mini Program.

Next steps
To launch your Mini Program, perform the following operations:
Register a domain name. For more information, see Domain Name Registration.
Apply for an SSL certificate and configure the certificate on the server. For more information, see Apply for a free SSL certificate of the personal edition.
Upload the Mini Program and submit it for review. For more information, see Mini Program Release.
Once approved, release the Mini Program manually. It will then be available in the WeChat client.









in the Actions column, and then click Stop in the panel that appears.