Web hosting is a sub-module of LeanEngine that allows you to develop a web application with PHP. It provides functions including cloud functions, hooks, hosting for static files, and custom routing, with your own domains bound to the service. You can use it to create a landing or download page for your mobile application, develop an admin console or a complete website, or run custom logic that has to be on the server side.
If you don't know how to create a LeanEngine project, debug it locally, or deploy it to the cloud, please first read LeanEngine Quick Start. Other related documents include:
Provided that you have [installed the command-line tool(leanengine_cli.html#installation), to create a new project from our example skelton, you just need one command:
lean init
Follow the prompts to enter the project information.
Then use composer to install third-party dependencies:
composer install
Running and Debugging Locally
Once all dependencies are installed, you can use our command-line interface in the project root directory to start a development server:
Run the following command in your project root directory:
lean deploy
Setting up Second-Level Domains
In the "Web Hosting Domain" section of your app's Dashboard > LeanEngine > Settings, you can fill in a custom second-level domain. For example, if you set it to be myapp, you can access your website through http://myapp.avosapps.us.
You may need to wait for a few hours until DNS settings take effect.
Our second-level domains support HTTPS by default.
If no request has been made to your app within the past 30 days and you haven't purchased a standard instance, the second-level domain may be recycled.
Project Skeleton
Your project has to follow the following structure to be recognized by LeanEngine and operate properly.
A LeanEngine PHP project must contain $PROJECT_DIR/public/index.php as the startup file for the whole project.
LeanEngine provides PHP 5.6 by default. If you need a specified version of PHP, please add it into composer.json:
"require": {
"php": "7.0"
}
LeanEngine supports version 5.6, 7.0, 7.1, 7.2, 7.3, and 7.4 at this time. We will keep adding supports for new versions released in the future.
By default, all versions of PHP have the following extensions enabled: fpm, curl, mysql, zip, xml, mbstring, gd, soap.
PHP 7.0 and above also have the mongodb extension enabled by default.
The extension mcrypt has been removed from the core of PHP 7.2 and is made optional in LeanEngine. You may enable it by adding ext-mcrypt: * into require of composer.json. Note that the time consumed for deployment will increase if mcrypt is enabled, so you may keep it off if you do not need it.
If you need to use other extensions, please submit a ticket.
LeanEngine PHP does not depend on any third-party frameworks, so you may use any frameworks you are familiar with for your project or choose not to use one. Make sure your project can be started by running public/index.php.
By default, a PHP-FPM Worker is assigned to every 64 MB memory of a PHP project. You can change the setting in "Custom environment variables" of LeanEngine's settings page by adding an environment variable with PHP_WORKERS as the name and a number as the value. Keep in mind that if the value is too low, there may be insufficient Workers for new requests, and if the value is too high, requests may not be successfully processed due to low memory space.
If your project directory contains composer.lock, dependencies will be installed according to the versions specified in this file.
Local repositories of type path are not supported since composer.json and/or composer.lock will be copied to a dedicated directory to install the dependencies during the build process.
Therefore, if your project uses path local repositories, please change them to other types such as vcs.
Using LeanStorage
LeanEngine uses LeanCloud PHP SDK which contains the LeanStorage PHP SDK. You can use the APIs provided by it to persist your data. See LeanStorage PHP Guide for more information.
LeanCloud PHP SDK provides the middleware that supports the Slim framework which is used in the example project. You can follow the way it is used in the example project.
If you choose to start from scratch, you need to configure it as follows:
Then configure dependency by executing the following command under the project root directory to add the dependency of the LeanCloud PHP SDK:
composer require leancloud/leancloud-sdk
Then initialize the middleware by using your App Key:
use \LeanCloud\Client;
Client::initialize(
getenv("LC_APP_ID"), // Obtain App ID from environment variable LC_APP_ID
getenv("LC_APP_KEY"), // Obtain App Key from environment variable LC_APP_KEY
getenv("LC_APP_MASTER_KEY") // Obtain Master Key from environment variable LC_APP_MASTER_KEY
);
// Delete the following line if you don't need to use the Master Key
Client::useMasterKey(true);
Health Monitoring
While your project is being deployed, LeanEngine's hypervisor will check if it is started successfully every second. The deployment is considered a failure if the check still fails after 30 seconds. Even after the project is deployed successfully, we still run health checks regularly to ensure that your app is running normally. If the check fails, the LeanEngine hypervisor will automatically restart your app.
The URLs for health monitoring include the index page of your project (/) and /__engine/1/ping which is handled by the PHP SDK. As long as one of them returns the HTTP status code 200, the project is considered to be normal. So make sure your program uses the PHP SDK or has its index page return 200 as the HTTP status code. Besides this, in order to support cloud functions and hooks in LeanEngine, the hypervisor will use the URL /1.1/functions/_ops/metadatas to communicate with the PHP SDK. Please make sure to have this URL handled by the PHP SDK or return 404 as the HTTP status code to indicate that cloud functions and hooks are not used.
LeanCloud PHP SDK will automatically handle this URL. Simply add the middleware to the request processing chain:
$engine = new SlimEngine();
$app->add($engine);
If you didn't use LeanCloud PHP SDK, you need to handle the URL by yourself:
LeanEngine provides a module LeanCloud\Storage\CookieStorage that uses cookies to manage sessions of users (User). You can use it by adding the following code to app.php:
use \LeanCloud\Storage\CookieStorage;
// Store the session states to a cookie
Client::setStorage(new CookieStorage(60 * 60 * 24, "/"));
CookieStorage allows you to pass in an expiration time in milliseconds, as well as a path as the scope of the cookie. The time before expiration defaults to 7 days.
The current user can be obtained with User::getCurrentUser(). You can implement a site with login feature like this:
$app->get('/login', function($req, $res) {
// Render login page
});
// Handle login requests (may come from forms in the login page)
$app->post('/login', function($req, $res) {
$params = $req->getQueryParams();
try {
User::logIn($params["username"], $params["password"]);
// Jump to the profile page
return $res->withRedirect('/profile');
} catch (Exception $ex) {
// Login failed, jump to login page
return $res->withRedirect('/login');
}
});
// View profile
$app->get('/profile', function($req, $res) {
// Determine if the user has logged in
$user = User::getCurrentUser();
if ($user) {
// If the user has already logged in, send the current login user information
return $res->getBody()->write($user->getUsername());
} else {
// If not, jump to the login page
return $res->withRedirect('/login');
}
});
// Log out
$app->get('/logout', function($req, $res) {
User::logOut();
return $res->redirect("/");
});
You can implement a simple login page like this to be used with the handlers above:
Now define the handler function for uploading files, build a Form object, and parse req as a parameter. This will save the uploaded file into a temporary directory, and construct the files object:
If you need to save certain properties in the session, you can add a universal CookieStorage:
// Enable CookieStorage when the project starts
Client::setStorage(new CookieStorage());
// Use CookieStorage to store properties in the project
$cookieStorage = Client::getStorage();
$cookieStorage->set("key", "val");
Keep in mind that $_SESSION of PHP cannot work properly on LeanEngine. LeanEngine runs your project on multiple hosts and threads, so in-memory sessions cannot be shared. Therefore, we recommend that you use CookieStorage to store data attached to each session.
CSRF Tokens
If your project uses cookies as an authentication method (like the SDK's CookieSession middleware), then there is a risk of CSRF attack which allows other sites to forge malicious requests with valid cookies.
CSRF tokens can be used to defend such attacks. A CSRF token is a random string generated by the server and passed to the client (usually through cookie). When the client makes a request, it must include the same CSRF token in the request body or the header. The server then verifies if the CSRF token is valid before processing the request.
Redirecting to HTTPS
For security consideration, it is recommended that all sites use HTTPS by default. LeanEngine supports such feature with a middleware that forces your website {App Domain}.avosapps.us to be accessed via HTTPS. Simply add the following code to have it enabled:
After your site is deployed to the production environment, all users accessing your website's second-level domain through HTTP will be redirected to HTTPS-enabled URLs.
Deploying and Publishing
Deploying with Command-Line Interface
Run the following command in your project root directory:
lean deploy
The command-line interface makes it easy to deploy projects, publish projects, view project status, and view logs. It allows you to deploy the same project to multiple applications as well. See Command-Line Interface Guide for more instructions.
Dependency Caching
LeanEngine implements a caching mechanism to speed up the build process (the process that installs dependencies for your project). For each new build, if the dependencies are not changed, the dependencies installed in the past will be reused and only the project code will be replaced.
The cached dependencies may become ineffective for various reasons, so it's not guaranteed that every build will make use of them.
If you are encountering problems with installing dependencies, you can enable the "Download latest dependencies" option when deploying on the web console, or add the --no-cache option when deploying with the command-line interface.
lean deploy --no-cache
Deploying from Git Repository
You can also deploy your project from a Git repository. LeanCloud doesn't offer version control services, so you need to push the project to a Git repository of your own choice. Good third-party websites that provide Git hosting services include GitHub, BitBucket, and GitLab.
After you push your code to a repository accessible from the Internet, please enter the URL of the Git repository (like https://github.com/<username>/<repoName>.git) into LeanEngine's settings page on the web console.
If the repository is private, you need to provide an SSH address (git@github.com:<username>/<repoName>.git) instead. You also need to provide the public key generated by LeanEngine as a deploy key to the Git service provider. For example, if you are using GitHub, you can add a deploy key by going to the repository's Settings > Deploy keys and click on Add deploy key.
After this, you will be able to deploy your project on the web console. It will deploy the code of the master branch by default, but you can specify a branch name, a label, or a specific commit when deploying.
If your repository contains submodules, LeanEngine will pull them automatically.
You can also set up a webhook so that each time you make a push to the Git repository, your project will be deployed from it.
To do so, go to your app's Dashboard > LeanEngine > Deploy > Deploy from git > Auto deploy to obtain the deploy token and webhook URL.
You can use the deploy token to construct HTTP requests to trigger deployments.
Filling in the code repository branch and LeanEngine environment, a corresponding webhook URL will be generated automatically.
The code from the specified branch will be deployed to the specified environment once the webhook URL receives any POST request.
For example, if you are using GitHub, you can go to your repository's Settings > Webhooks and add the URL as the Payload URL of a new webhook (leave other settings as default). By doing so, the designated branch will be deployed to LeanEngine each time you make a push to any existing branch. The reason we cannot perform a deployment based on the branch you are pushing to is that GitHub doesn't allow you to set up webhooks for specific branches, plus LeanEngine is not designing this feature for any specific platforms so it couldn't read the contents in a POST request.
However, you can use GitHub Actions to control the timing of your deployment in a more granular way. Please refer to the example shown on the dashboard.
Staging Environment and Production Environment
By default, you application has a production environment for LeanEngine and the corresponding domain is {App Domain}.avosapps.us. There is a trial instance in the production environment to run your project.
When the trial instance in the production environment is upgraded to a standard instance, there will be a new staging environment with the corresponding domain stg-{App Domain}.avosapps.us, with both environments accessing the same LeanStorage data. You can test your code by deploying it to the staging environment each time you make a change and publish it to the production environment when ready. If you want to have a test environment with an independent data source, you can create a separate application.
If you encounter the "Application not Found" error when accessing LeanEngine, it is usually because your code hasn't been deployed to the corresponding environment. This may be triggered when you attempt to access the staging environment when there isn't one or try to access the production environment without publishing your project.
Sometimes you may need to know the environment the current process is running in (development, staging, or production) and have your project behave differently:
$env = getenv("LEANCLOUD_APP_ENV");
if ($env === "development") {
// Development environment started by command-line interface
} else if ($env === "production") {
// Production environment
} else {
// Staging environment
}
In SDK, you can specify the environment where requests from clients are sent to:
AV.setProduction(true); // Production environment (default)
AV.setProduction(false); // Staging environment
leancloud.use_production(True) # Production environment (default)
leancloud.use_production(False) # Staging environment
# Call it before `leancloud.init`
LeanClient::useProduction(true); // Production environment (default)
LeanClient::useProduction(false); // Staging environment
AVCloud.setProductionMode(true); // Production environment (default)
AVCloud.setProductionMode(false); // Staging environment
Cloud Runtime Environment
System-Level Dependencies
You can specify system-level dependencies by changing systemDependencies of leanengine.yaml:
systemDependencies:
- imagemagick
LeanEngine supports the following dependencies:
ffmpeg: An audio and video processing tool and library.
imagemagick: An image processing tool and library.
phantomjs: A headless WebKit browser (deprecated).
chrome-headless: A headless Chrome browser (takes more time to be deployed and consumes a lot of CPU and memory; if you use puppeter, you need to pass {executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', '--disable-setuid-sandbox']} to puppeteer.launch; does not support Java).
node-canvas: System dependencies required for installing node-canvas (you still need to install node-canvas by yourself).
python-talib: A library for performing technical analysis of financial market data.
Adding system dependencies will slow down the deployment. Please don't add unused dependencies.
Environment Variables
LeanEngine provides the following environment variables by default:
Variable Name
Description
LEANCLOUD_APP_ID
The App ID of the current application.
LEANCLOUD_APP_KEY
The App Key of the current application.
LEANCLOUD_APP_MASTER_KEY
The Master Key of the current application.
LEANCLOUD_APP_ENV
Current environment:
Depending on how you start the local development instance, this variable may not exist or may be set to development.
Staging environment: stage.
Production environment: production.
LEANCLOUD_APP_PORT
The port listened by the project. Other ports are not accessible from the public network.
LEANCLOUD_API_SERVER
The URL used to access LeanStorage (looks like https://api.leancloud.cn). It is based on the location of the data center used to host the project and may change over time. You can use it when making requests to LeanStorage or other LeanCloud services with our REST API. Please do not use https://api.leancloud.cn directly in LeanEngine.
LEANCLOUD_AVAILABLE_CPUS
The number of CPUs available to the LeanEngine instance. It is based on the size of your instance and should be larger than 1 for large instances (like those with 2 CPUs and 1024 MB memory). Please do not use the number of CPUs of the operating system directly, or your project may be terminated if excessive threads are opened up.
LEANCLOUD_APP_GROUP
The group this instance belongs to. When using the LeanEngine Group Management feature, this becomes the name of the group.
LEANCLOUD_REGION
The region where the instance is located at. For LeanCloud International version, the value is US.
LEANCLOUD_VERSION_TAG
The instance deployment version.
You can also add custom environment variables in your app's Dashboard > LeanEngine > Settings > Custom environment variables. Variable names can only contain letters, numbers, and underscores, and can only begin with a letter. The value must be a string. The updated environment variables will take effect after the next deployment.
A common practice of using environment variables is to store configurations with them. By doing so, the behavior of your project can be changed by updating environment variables only without touching the code. You can also store secrets keys of third-party services as environment variables so that they are not exposed in the code.
The environment variables provided by LeanEngine cannot be overwritten by custom environment variables.
By default, the built-in and custom environment variables can only be read by the application at runtime.
If you want to read these environment variables while installing dependencies or compiling, add the following line to leanengine.yaml:
exposeEnvironmentsOnBuild: true
Load Balancing
On LeanEngine, requests from the clients go through a load balancer before they reach to your app. The load balancer handles SSL encryption and decryption, data compression, etc., so you don't have to add HTTPS- or gzip-related functions to your app.
Since the load balancer handles SSL encryption and decryption, the request URLs received by the web framework always start with http.
You need to check the X-Forwarded-Proto HTTP header to detect if the original requests use HTTP or HTTPS.
The load balancer also enforces limitations that the maximum size of each request is 100 MB (including uploading files to LeanEngine), the maximum time for processing each request is 60 seconds, and a WebSocket will be disconnected if no data goes through in the past 60 seconds.
File System
You can write temporary files into /home/leanengine or /tmp, up to 1 GB in total.
Each time a project is deployed to LeanEngine, a new container will be created. Even though you don't initiate deployments, the system may also occasionally perform clean-ups. Therefore, you can't treat the local file system as a persistent storage.
If the files written are relatively large, we recommend that you delete the files after using them. If more than 1 GB of disk space is used, you may receive "Disk quota exceeded" errors. In this situation, you can redeploy your project to clear out the files.
You can also export the logs of the past seven days to local files with the command-line interface.
Each line of log can contain no more than 4096 characters and the characters exceeding the limit will be discarded. There could be no more than 600 lines of logs output per minute and the lines exceeding the limit will be discarded.
We will try our best to avoid changing public IP addresses, but cannot eliminate the possibility of making changes. In the case of IP-related problems, please double check if the public IP addresses are changed.
Custom Domains
We recommend that you register your own domain and bind it to your LeanEngine production environment. You can bind a custom domain at Account settings > Domain binding.
PHP Web Hosting Guide
Web hosting is a sub-module of LeanEngine that allows you to develop a web application with PHP. It provides functions including cloud functions, hooks, hosting for static files, and custom routing, with your own domains bound to the service. You can use it to create a landing or download page for your mobile application, develop an admin console or a complete website, or run custom logic that has to be on the server side.
If you don't know how to create a LeanEngine project, debug it locally, or deploy it to the cloud, please first read LeanEngine Quick Start. Other related documents include:
This guide uses PHP as an example, but LeanEngine supports many other languages as well. You can choose the one you are familiar with for development:
Starting with the Example Project
Provided that you have [installed the command-line tool(leanengine_cli.html#installation), to create a new project from our example skelton, you just need one command:
Follow the prompts to enter the project information.
Then use
composer
to install third-party dependencies:Running and Debugging Locally
Once all dependencies are installed, you can use our command-line interface in the project root directory to start a development server:
For more information regarding command-line interface and local debugging, see Command-Line Interface Guide.
Deploying to the Cloud
Run the following command in your project root directory:
Setting up Second-Level Domains
In the "Web Hosting Domain" section of your app's Dashboard > LeanEngine > Settings, you can fill in a custom second-level domain. For example, if you set it to be
myapp
, you can access your website throughhttp://myapp.avosapps.us
.You may need to wait for a few hours until DNS settings take effect.
Our second-level domains support HTTPS by default.
If no request has been made to your app within the past 30 days and you haven't purchased a standard instance, the second-level domain may be recycled.
Project Skeleton
Your project has to follow the following structure to be recognized by LeanEngine and operate properly.
A LeanEngine PHP project must contain
$PROJECT_DIR/public/index.php
as the startup file for the whole project.LeanEngine provides PHP 5.6 by default. If you need a specified version of PHP, please add it into
composer.json
:LeanEngine supports version
5.6
,7.0
,7.1
,7.2
,7.3
, and7.4
at this time. We will keep adding supports for new versions released in the future.By default, all versions of PHP have the following extensions enabled:
fpm
,curl
,mysql
,zip
,xml
,mbstring
,gd
,soap
. PHP 7.0 and above also have themongodb
extension enabled by default. The extensionmcrypt
has been removed from the core of PHP 7.2 and is made optional in LeanEngine. You may enable it by addingext-mcrypt: *
intorequire
ofcomposer.json
. Note that the time consumed for deployment will increase ifmcrypt
is enabled, so you may keep it off if you do not need it. If you need to use other extensions, please submit a ticket.LeanEngine PHP does not depend on any third-party frameworks, so you may use any frameworks you are familiar with for your project or choose not to use one. Make sure your project can be started by running
public/index.php
.By default, a PHP-FPM Worker is assigned to every 64 MB memory of a PHP project. You can change the setting in "Custom environment variables" of LeanEngine's settings page by adding an environment variable with
PHP_WORKERS
as the name and a number as the value. Keep in mind that if the value is too low, there may be insufficient Workers for new requests, and if the value is too high, requests may not be successfully processed due to low memory space.If your project directory contains
composer.lock
, dependencies will be installed according to the versions specified in this file.Local repositories of type
path
are not supported sincecomposer.json
and/orcomposer.lock
will be copied to a dedicated directory to install the dependencies during the build process. Therefore, if your project usespath
local repositories, please change them to other types such asvcs
.Using LeanStorage
LeanEngine uses LeanCloud PHP SDK which contains the LeanStorage PHP SDK. You can use the APIs provided by it to persist your data. See LeanStorage PHP Guide for more information.
LeanCloud PHP SDK provides the middleware that supports the Slim framework which is used in the example project. You can follow the way it is used in the example project.
If you choose to start from scratch, you need to configure it as follows:
composer
.Then configure dependency by executing the following command under the project root directory to add the dependency of the LeanCloud PHP SDK:
Then initialize the middleware by using your App Key:
Health Monitoring
While your project is being deployed, LeanEngine's hypervisor will check if it is started successfully every second. The deployment is considered a failure if the check still fails after 30 seconds. Even after the project is deployed successfully, we still run health checks regularly to ensure that your app is running normally. If the check fails, the LeanEngine hypervisor will automatically restart your app.
The URLs for health monitoring include the index page of your project (
/
) and/__engine/1/ping
which is handled by the PHP SDK. As long as one of them returns the HTTP status code200
, the project is considered to be normal. So make sure your program uses the PHP SDK or has its index page return200
as the HTTP status code. Besides this, in order to support cloud functions and hooks in LeanEngine, the hypervisor will use the URL/1.1/functions/_ops/metadatas
to communicate with the PHP SDK. Please make sure to have this URL handled by the PHP SDK or return404
as the HTTP status code to indicate that cloud functions and hooks are not used.LeanCloud PHP SDK will automatically handle this URL. Simply add the middleware to the request processing chain:
If you didn't use LeanCloud PHP SDK, you need to handle the URL by yourself:
Session Management
LeanEngine provides a module
LeanCloud\Storage\CookieStorage
that uses cookies to manage sessions of users (User
). You can use it by adding the following code toapp.php
:CookieStorage
allows you to pass in an expiration time in milliseconds, as well as a path as the scope of the cookie. The time before expiration defaults to 7 days.The current user can be obtained with
User::getCurrentUser()
. You can implement a site with login feature like this:You can implement a simple login page like this to be used with the handlers above:
Implementing Common Features
Sending HTTP Requests
LeanEngine PHP environment supports the built-in
curl
module, but we recommend that you use a third-party library like guzzle to send HTTP requests.To install
guzzle
:Code example:
Obtaining Client IP
You can get the client's IP directly from the
x-real-ip
field in the HTTP header:Uploading Files
Websites hosted on LeanEngine can handle file uploads with file-related APIs of LeanCloud PHP SDK.
Assuming the frontend HTML code looks like this:
Now define the handler function for uploading files, build a
Form
object, and parsereq
as a parameter. This will save the uploaded file into a temporary directory, and construct thefiles
object:Sessions
If you need to save certain properties in the session, you can add a universal
CookieStorage
:Keep in mind that
$_SESSION
of PHP cannot work properly on LeanEngine. LeanEngine runs your project on multiple hosts and threads, so in-memory sessions cannot be shared. Therefore, we recommend that you useCookieStorage
to store data attached to each session.CSRF Tokens
If your project uses cookies as an authentication method (like the SDK's
CookieSession
middleware), then there is a risk of CSRF attack which allows other sites to forge malicious requests with valid cookies.CSRF tokens can be used to defend such attacks. A CSRF token is a random string generated by the server and passed to the client (usually through cookie). When the client makes a request, it must include the same CSRF token in the request body or the header. The server then verifies if the CSRF token is valid before processing the request.
Redirecting to HTTPS
For security consideration, it is recommended that all sites use HTTPS by default. LeanEngine supports such feature with a middleware that forces your website
{App Domain}.avosapps.us
to be accessed via HTTPS. Simply add the following code to have it enabled:After your site is deployed to the production environment, all users accessing your website's second-level domain through HTTP will be redirected to HTTPS-enabled URLs.
Deploying and Publishing
Deploying with Command-Line Interface
Run the following command in your project root directory:
The command-line interface makes it easy to deploy projects, publish projects, view project status, and view logs. It allows you to deploy the same project to multiple applications as well. See Command-Line Interface Guide for more instructions.
Dependency Caching
LeanEngine implements a caching mechanism to speed up the build process (the process that installs dependencies for your project). For each new build, if the dependencies are not changed, the dependencies installed in the past will be reused and only the project code will be replaced.
The cached dependencies may become ineffective for various reasons, so it's not guaranteed that every build will make use of them.
If you are encountering problems with installing dependencies, you can enable the "Download latest dependencies" option when deploying on the web console, or add the
--no-cache
option when deploying with the command-line interface.Deploying from Git Repository
You can also deploy your project from a Git repository. LeanCloud doesn't offer version control services, so you need to push the project to a Git repository of your own choice. Good third-party websites that provide Git hosting services include GitHub, BitBucket, and GitLab.
After you push your code to a repository accessible from the Internet, please enter the URL of the Git repository (like
https://github.com/<username>/<repoName>.git
) into LeanEngine's settings page on the web console.If the repository is private, you need to provide an SSH address (
git@github.com:<username>/<repoName>.git
) instead. You also need to provide the public key generated by LeanEngine as a deploy key to the Git service provider. For example, if you are using GitHub, you can add a deploy key by going to the repository's Settings > Deploy keys and click on Add deploy key.After this, you will be able to deploy your project on the web console. It will deploy the code of the
master
branch by default, but you can specify a branch name, a label, or a specific commit when deploying.If your repository contains submodules, LeanEngine will pull them automatically.
You can also set up a webhook so that each time you make a push to the Git repository, your project will be deployed from it. To do so, go to your app's Dashboard > LeanEngine > Deploy > Deploy from git > Auto deploy to obtain the deploy token and webhook URL. You can use the deploy token to construct HTTP requests to trigger deployments. Filling in the code repository branch and LeanEngine environment, a corresponding webhook URL will be generated automatically. The code from the specified branch will be deployed to the specified environment once the webhook URL receives any POST request.
For example, if you are using GitHub, you can go to your repository's Settings > Webhooks and add the URL as the Payload URL of a new webhook (leave other settings as default). By doing so, the designated branch will be deployed to LeanEngine each time you make a push to any existing branch. The reason we cannot perform a deployment based on the branch you are pushing to is that GitHub doesn't allow you to set up webhooks for specific branches, plus LeanEngine is not designing this feature for any specific platforms so it couldn't read the contents in a POST request. However, you can use GitHub Actions to control the timing of your deployment in a more granular way. Please refer to the example shown on the dashboard.
Staging Environment and Production Environment
By default, you application has a production environment for LeanEngine and the corresponding domain is
{App Domain}.avosapps.us
. There is a trial instance in the production environment to run your project.When the trial instance in the production environment is upgraded to a standard instance, there will be a new staging environment with the corresponding domain
stg-{App Domain}.avosapps.us
, with both environments accessing the same LeanStorage data. You can test your code by deploying it to the staging environment each time you make a change and publish it to the production environment when ready. If you want to have a test environment with an independent data source, you can create a separate application.If you encounter the "Application not Found" error when accessing LeanEngine, it is usually because your code hasn't been deployed to the corresponding environment. This may be triggered when you attempt to access the staging environment when there isn't one or try to access the production environment without publishing your project.
Sometimes you may need to know the environment the current process is running in (development, staging, or production) and have your project behave differently:
In SDK, you can specify the environment where requests from clients are sent to:
Cloud Runtime Environment
System-Level Dependencies
You can specify system-level dependencies by changing
systemDependencies
ofleanengine.yaml
:LeanEngine supports the following dependencies:
ffmpeg
: An audio and video processing tool and library.imagemagick
: An image processing tool and library.phantomjs
: A headless WebKit browser (deprecated).chrome-headless
: A headless Chrome browser (takes more time to be deployed and consumes a lot of CPU and memory; if you usepuppeter
, you need to pass{executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', '--disable-setuid-sandbox']}
topuppeteer.launch
; does not support Java).node-canvas
: System dependencies required for installingnode-canvas
(you still need to installnode-canvas
by yourself).python-talib
: A library for performing technical analysis of financial market data.Adding system dependencies will slow down the deployment. Please don't add unused dependencies.
Environment Variables
LeanEngine provides the following environment variables by default:
LEANCLOUD_APP_ID
LEANCLOUD_APP_KEY
LEANCLOUD_APP_MASTER_KEY
LEANCLOUD_APP_ENV
development
.stage
.production
.LEANCLOUD_APP_PORT
LEANCLOUD_API_SERVER
https://api.leancloud.cn
). It is based on the location of the data center used to host the project and may change over time. You can use it when making requests to LeanStorage or other LeanCloud services with our REST API. Please do not usehttps://api.leancloud.cn
directly in LeanEngine.LEANCLOUD_AVAILABLE_CPUS
LEANCLOUD_APP_GROUP
LEANCLOUD_REGION
US
.LEANCLOUD_VERSION_TAG
You can also add custom environment variables in your app's Dashboard > LeanEngine > Settings > Custom environment variables. Variable names can only contain letters, numbers, and underscores, and can only begin with a letter. The value must be a string. The updated environment variables will take effect after the next deployment.
A common practice of using environment variables is to store configurations with them. By doing so, the behavior of your project can be changed by updating environment variables only without touching the code. You can also store secrets keys of third-party services as environment variables so that they are not exposed in the code.
The environment variables provided by LeanEngine cannot be overwritten by custom environment variables.
By default, the built-in and custom environment variables can only be read by the application at runtime. If you want to read these environment variables while installing dependencies or compiling, add the following line to
leanengine.yaml
:Load Balancing
On LeanEngine, requests from the clients go through a load balancer before they reach to your app. The load balancer handles SSL encryption and decryption, data compression, etc., so you don't have to add HTTPS- or gzip-related functions to your app. Since the load balancer handles SSL encryption and decryption, the request URLs received by the web framework always start with
http
. You need to check theX-Forwarded-Proto
HTTP header to detect if the original requests use HTTP or HTTPS.The load balancer also enforces limitations that the maximum size of each request is 100 MB (including uploading files to LeanEngine), the maximum time for processing each request is 60 seconds, and a WebSocket will be disconnected if no data goes through in the past 60 seconds.
File System
You can write temporary files into
/home/leanengine
or/tmp
, up to 1 GB in total.Each time a project is deployed to LeanEngine, a new container will be created. Even though you don't initiate deployments, the system may also occasionally perform clean-ups. Therefore, you can't treat the local file system as a persistent storage.
If the files written are relatively large, we recommend that you delete the files after using them. If more than 1 GB of disk space is used, you may receive "Disk quota exceeded" errors. In this situation, you can redeploy your project to clear out the files.
Logs
You can view LeanEngine's deployment and runtime logs at Dashboard > LeanEngine > App logs. The logs can be filtered by levels.
You can also export the logs of the past seven days to local files with the command-line interface.
Each line of log can contain no more than 4096 characters and the characters exceeding the limit will be discarded. There could be no more than 600 lines of logs output per minute and the lines exceeding the limit will be discarded.
LeanEngine's access logs can be exported at Dashboard > LeanEngine > Access logs.
Time Zones
The time zone used on the server is UTC.
Public IP Addresses
If you need to configure IP whitelists on third-party services and need to obtain LeanEngine's public IP addresses, please go to Dashboard > LeanEngine > Settings > Public IP addresses.
We will try our best to avoid changing public IP addresses, but cannot eliminate the possibility of making changes. In the case of IP-related problems, please double check if the public IP addresses are changed.
Custom Domains
We recommend that you register your own domain and bind it to your LeanEngine production environment. You can bind a custom domain at Account settings > Domain binding.