Build a high-availability WeChat Mini Program service

Updated at:
Copy as MD

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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

    image

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

  1. 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
    }
  2. 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:

    1. For information about ECS billing, see Billing overview.

    2. For information about CLB billing, see Billing overview.

    3. For information about EIP billing, see Billing overview.

  3. 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.

  4. 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/getServerInfo

    If 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:

  1. Step 1: Create a RAM role and attach it to the ECS instances

  2. Step 2: Log on to the ECS instances

  3. Step 3: Install Nginx

  4. Step 4: Develop the backend service

  5. Step 5: Install uWSGI Server

  6. Step 6: Configure and restart Nginx

  7. Step 7: Configure a listener

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.

  1. Create an instance RAM role.

    1. Log on to the RAM console as a RAM administrator.

    2. In the left-side navigation pane, choose Identities > Roles.

    3. On the Roles page, click Create Role.

      image

    4. On the Create Role page, select Alibaba Cloud Service for Select Trusted Entity, select a specific Alibaba Cloud service, and then click OK.

      image

      Note

      The available services for Trusted Service are listed in the console.

    5. (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.

        image

        image

      • Script editor

        In the Service field of the Principal, specify the Alibaba Cloud service.

        {
          "Version": "1",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "177*******6878@actiontrail.aliyuncs.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        }
    6. In the Create Role dialog box, enter a RAM Role Name and click OK.

  2. Attach the RAM role to the instances.

    1. Go to ECS console - Instances.

    2. In the top navigation bar, select the region and resource group of the resource that you want to manage. Region

    3. 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.

    4. 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.

  1. Go to ECS console - Instances.

  2. In the top navigation bar, select the region of the ECS instance.image.png

  3. Set the logon password for the ECS instance.

    1. 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.

      重置密码

      Important

      You 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.

    2. (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.

  4. 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).

    image

  5. Remotely connect to the ECS instance.

    1. Return to the Instances page and click Connect in the Actions column of the instance.

    2. In the Connect and Command dialog box, click Log on now next to Connect via Workbench.

    3. In the Log In to Instance dialog box, enter your logon information.

  6. Repeat the preceding steps to log on to the ECS02 instance.

Step 3: Install Nginx

  1. Run the command to install Nginx.

    sudo yum update && sudo yum -y install nginx
  2. Start Nginx.

    sudo systemctl start nginx
  3. Run the following command to check the running status of the Nginx service:

    If Active: active (running) is returned, Nginx is started.

    systemctl status nginx
  4. Repeat the preceding steps to install Nginx on the ECS02 instance.

Step 4: Develop the backend service

  1. Create a service directory.

    sudo mkdir /data && cd /data
  2. Create and edit the dependency file for the Python service.

    sudo vim requirements.txt
  3. After entering the Vim editor, press the i key to enter edit mode and paste the following content.

    wheel
    alibabacloud_credentials
    alibabacloud_ecs20140526
    Flask==2.0.3
  4. After pasting, press the Esc key, and enter :x to save the changes and exit.

  5. Run the following command to install the dependencies:

    sudo pip3 install --upgrade pip && sudo pip3 install -r requirements.txt
  6. Create and edit the code file for the Python service.

    sudo vim get_server_info.py
  7. After entering the Vim editor, press the i key to enter edit mode and paste the following content.

    Note

    In the code, the value of ecs_ram_role must be the name of the RAM role that you created.

    In the code, the value of region must 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()
  8. After pasting, press the Esc key, and enter :x to save and exit.

  9. 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.

  1. Run the command to install uWSGI.

    sudo pip3 install uwsgi
  2. Create a uWSGI configuration file.

    cd /data && sudo vim uwsgi.ini
  3. In the Vim editor, press the i key 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.log
  4. After pasting the content, press the Esc key, enter :x, and then press the Enter key to save the file and exit the editor.

  5. Run the which uwsgi command to find and confirm the full path of the uwsgi executable file.

    The following information is returned:

    /usr/local/bin/uwsgi
  6. Start the uWSGI server.

    sudo /usr/local/bin/uwsgi uwsgi.ini
  7. Run 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

    uwsgi..png

  8. 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.

  1. Create a configuration file.

    sudo vim /etc/nginx/conf.d/app.conf
  2. In the Vim editor, press the i key 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;
        }
    }
  3. After pasting the content, press the Esc key, enter :x, and then press the Enter key to save the file and exit the editor.

  4. Restart Nginx.

    sudo nginx -s reload
  5. Verify that the configuration is successful.

    Note

    If the service fails to start, check the /data/uwsgi.log file for the cause.

    curl http://127.0.0.1/ecs/getServerInfo

    If Invalid Parameter is returned, the configuration is successful.

  6. 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.

  1. Log on to the CLB console.

  2. On the Instances page, click the ID of the created CLB instance.

  3. On the Listeners tab, click Add Listener.

  4. 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

  5. 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.

  6. Enter the ports for ECS01 and ECS02. In this tutorial, set the ports to 80 for both instances and click Next.

  7. 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.

  1. 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.

    mp注册

  2. 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.

    setting

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.

  1. Go to the Node.js page to download and install the Node.js development environment.

  2. Download and install WeChat DevTools. For more information, see Download DevTools.

  3. Open WeChat DevTools and use WeChat to scan the QR code to log on.

  4. Click the plus sign (+) to create a sample WeChat Mini Program project.

    mp创建

  5. 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.

    mpcreate

  6. 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.

  1. 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 .wxml file defines the structure of the current page. All pages in the Mini Program must be declared in the app.json file. 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.json
  2. Edit the app.json file to change the page title of the Mini Program to ECS Assistant. The following code provides the modified content of the app.json file.

    {
      "pages":[
        "pages/index/index",
        "pages/logs/logs"
      ],
      "window":{
        "backgroundTextStyle":"light",
        "navigationBarBackgroundColor": "#fff",
        "navigationBarTitleText": "ECS Assistant",
        "navigationBarTextStyle":"black"
      },
      "style": "v2",
      "sitemapLocation": "sitemap.json"
    }
  3. Edit the pages/index/index.wxss file to define the style of the index page. The following code provides the modified content of the index.wxss file.

    .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;
    }
  4. Edit the pages/index/index.js file to define the blur event for the search box. The following code provides the modified content of the index.js file.

    Note

    Replace <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
              })
            }
          }
    
        })
      }
    })
  5. Edit the pages/index/index.wxml file to create the display interface. The following code provides the modified content of the index.wxml file.

    <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>
  6. After saving the file, the editor automatically refreshes. If the following interface appears, the Mini Program is running.

    image..png

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:

  1. Log on to the ECS console, find the target instance, click image.png in the Actions column, and then click Stop in the panel that appears.

  2. 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.

image.png

Next steps

To launch your Mini Program, perform the following operations:

  1. Register a domain name. For more information, see Domain Name Registration.

  2. 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.

  3. 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.

Related documentation