Serverless Practice-Node Services are deployed online

This is the 16th day of my participation in Gwen Challenge

This article aims to help those who do not know o&M/network/server knowledge to realize the online deployment of Node service (back-end application developed by Node) without renting a cloud server

This series has been updated:

  • Serverless Practices – Static Web hosting

Super picture warning!!

This hands-on Serverless series is expected to have several installments covering static sites, cloud functions, Node services, and more

If there is unclear, content error and so on, please correct the comments

Take Tencent Cloud Serverless service as an example

Create a Serverless application

Enter the console panel, usually in the upper right corner of the home page

Then locate the Serverless Application Center in the list of cloud products in the upper left corner

You should then see the following interface

Click New, and you’ll see a lot of templates to choose from, so let’s go ahead and select Express and click Next

The basic configuration includes:

  • App name: fill in whatever you want
  • Environment (dev/test/prod) : optional
  • Region (server location) : choose as you like

Advanced configurations include:

  • Memory: 128MB by default. You can select 256 MB or higher based on service requirements. The service will be dynamically expanded when the traffic is heavy (new service instances are created to share the traffic)
  • Timeout duration: 3s by default. It is recommended to lengthen the timeout duration (about 10s). Because the service has a cold startup problem, some requests may fail to be invoked during 3s because the service is not started or does not respond in time
  • Environment variables :(can be ignored, it is recommended to match in the. Env file of the project)

Fill in the basic information and then click Finish

Wait a few minutes for the service to complete initialization

You can see usage data on the Serverless Application Center home page

Online access address

After the application is created, you can see the online address of the back-end service on the card:

For example, I this demo service address: service-rbji0bev-1256505457.cd.apigw.tencentcs.com/release/

The default access effect is as follows:

Template source code

Select Development Deployment -> Update Application from the card

Next, select local development and click Download project

Template directory structure

/home/sugar/Downloads/source├ ─ ─ index. The HTML ├ ─ ─ layer | └ ─ ─ serverless. Yml ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ serverless. Yml ├ ─ ─ SLS. Js └ ─ ─ src.map directory: 1 file: 7Copy the code

The serverless. Yml configuration file and sls.js are the only ones of concern

The serverless. Yml file is a configuration file of the Serverless service

There are no special requirements and we can just ignore it, it’s generated and it corresponds to the project that you’re creating

The sls.js file is the source code of our project

SLS. Js source code

Check out the full source code
const express = require('express')
const path = require('path')
const app = express()

// Routes
app.get(` / `.(req, res) = > {
  res.sendFile(path.join(__dirname, 'index.html'))
})

app.get('/user'.(req, res) = > {
  res.send([
    {
      title: 'serverless framework'.link: 'https://serverless.com'
    }
  ])
})

app.get('/user/:id'.(req, res) = > {
  const id = req.params.id
  res.send({
    id: id,
    title: 'serverless framework'.link: 'https://serverless.com'
  })
})

app.get('/ 404'.(req, res) = > {
  res.status(404).send('Not found')
})

app.get('/ 500'.(req, res) = > {
  res.status(500).send('Server Error')})// Error handler
app.use(function(err, req, res, next) {
  console.error(err)
  res.status(500).send('Internal Serverless Error')
})

app.listen(8080)

module.exports = app
Copy the code

Leave out the extraneous code, and there are only four lines in the core

const express = require('express')
const app = express()

// Omits the registered route

// omit Error handler

app.listen(8080)

module.exports = app
Copy the code
  1. The introduction of express
  2. performexpressinstantiation
  3. The Listen method is called to listen on a port to start the service foo
  4. Export this instance

So to deploy our own Node-Express project (similar to other Node projects), there are two simple steps:

  1. Copy the serverless. Yml file to the corresponding directory of your project
  2. Modify the sls.js file to import your own Express instance and export it

See below for an example of an existing Express project transformation

Serverless. Yml Configuration file description

Only focus on the serverless. Yml file in the root directory, not layer/serverless

component: express
name: express-jskJUp-v4
org: '1256505457'
app: suixinsuoyu
stage: dev
inputs:
  src:
    src: . /
    exclude:              Directory or file that needs to be excluded when uploading code
      - .env
      - node_modules/**
  region: ap-chengdu
  runtime: Nodejs10.15
  apigatewayConf:
    protocols:
      - http
      - https
    environment: release
    serviceTimeout: 60
    autoCreateDns: false
  isAutoCiDeploy: false
  functionConf:
    eip: false
    timeout: 3           If the interface does not respond after the specified timeout, an error will be returned
    memorySize: 128      The size of memory used by the configured service
  layers:
    - name: '${output:${stage}:${app}:suixinsuoyu-layer.name}'
      version: '${output:${stage}:${app}:suixinsuoyu-layer.version}'
Copy the code

We only care about the annotated items in the configuration

Different framework/service type configurations vary slightly

A complete configuration introduction is available in the documentation: Serverless Application Center – YML file specification

The test found some problems with the dependencies in package.json automatically installed by the service. To avoid the impact of the problems, you need to upload the local node_modules directory

Examples of existing Express project transformation

  • Warehouse complete source code

Original directory structure

├ ─ ─ the README. Md ├ ─ ─ _tests_ | └ ─ ─ index. The test. The js ├ ─ ─ docs | ├ ─ ─ API | └ ─ ─ the md ├ ─ ─ jest. Config. Js ├ ─ ─ package. The json ├ ─ ─ the SRC | ├ ─ ─ app. Js | ├ ─ ─ the config | ├ ─ ─ constants | ├ ─ ─ the db | ├ ─ ─ routes | └ ─ ─ utils └ ─ ─ yarn. The lockCopy the code

SRC /app.js source code, omit some code

const dotenv = require('dotenv')
const express = require('express')

// read - prints environment variables
// Read the. Env environment variable configuration file
console.log(dotenv.config())

const { serverConfig } = require('./config')
// All routes for the user
const mainRouter = require('./routes')

// Instantiate Express
const app = express()

// Register some middleware
app.use(express.urlencoded({ extended: false }))
app.use(express.json({ strict: true }))

// The route entered first (global interceptor)
app.route(The '*').all(async (req, res, next) => {
  // ------- cross-domain support -----------
  // Login verification
  next()
})
// Register all routes
app.use(mainRouter)

app.listen(serverConfig.port, serverConfig.hostname, () = > {
  console.log(`server start at ${serverConfig.hostname}:${serverConfig.port}`)})Copy the code

Reform steps

Refer to the two steps described above:

  1. sls.js.serverless.ymlCopy the files (3 in total). The copied directories are as follows
├ ─ ─ LICENSE ├ ─ ─ the README. Md ├ ─ ─ _tests_ | └ ─ ─ index. The test. The js ├ ─ ─ docs | ├ ─ ─ API | └ ─ ─ the md ├ ─ ─ jest. Config. Js ├ ─ ─ layer | └ ─ ─ serverless. Yml# 1├ ─ ─ package. Json ├ ─ ─ serverless. Yml# 2├ ─ ─ SLS. Js# 3├ ─ ─ the SRC | ├ ─ ─ app. Js | ├ ─ ─ the config | ├ ─ ─ constants | ├ ─ ─ the db | ├ ─ ─ routes | └ ─ ─ utils └ ─ ─ yarn. The lock directory: 10 file: 11Copy the code
  1. Minor modifications to the source code in app.js and sls.js

SRC/app. Js changes

// Omit other code
app.listen(serverConfig.port, serverConfig.hostname, () = > {
  console.log(`server start at ${serverConfig.hostname}:${serverConfig.port}`)})// The added line exports the app instance
module.exports = app
Copy the code

SLS. Js source code

// Import the exported app
const app = require('./src/app')

// Export it again
module.exports = app
Copy the code

We’re done. We’re done

Online WebIDE view source code

Go back to Serverless- Application Select the application we just created and return to the familiar card page

Clicking on the blue function name of the cloud function (which is a link) takes you to the WebIDE page

We can view the source code of our template project through WebIDE, and there is some code that is not in the template, we do not care about it and do not modify it

The deployment of online

Let’s make a quick change to our template project and deploy it online

Modifying a Template

  • Template modified after the complete source code
Click to see the changes to index.html
<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
  <title>Do what you like with Demo-express.js</title>
</head>

<body>
  <h1>Interface list (Demo as you like)</h1>
  <ul>
    <li><span>Home page</span><span>GET:</span>/</li>
    <li><span>Get random numbers</span><span>GET:</span>/random/code</li>
    <li><span>The login</span><span>POST:</span>/user/login</li>
    <li><span>404</span><span>GET:</span>/ 404</li>
  </ul>
</body>

</html>
Copy the code
Click here to see the changes to sls.js
const express = require('express')
const path = require('path')
const app = express()

// Routes
app.get(` / `.(req, res) = > {
  res.sendFile(path.join(__dirname, 'index.html'))
})

app.get('/random/code'.(req,res) = >{
  res.send({
    num:Math.random()
  })
})
app.post('/user/login'.(req, res) = > {
  res.send({
    code:0.data: {token:'test-token'
    },
    msg:'ok'
  })
})

app.get('/ 404'.(req, res) = > {
  res.status(404).send('Not found')})// Error handler
app.use(function(err, req, res, next) {
  console.error(err)
  res.status(500).send('Internal Serverless Error')
})

app.listen(8080)

module.exports = app

Copy the code

Lead the environment

  • Node.js

Make sure you have the Node.js environment on your computer

Open your terminal tools to see if you have the Node environment

node -v
Copy the code

Serverless Framework

Install the Serverless Framework

npm install -g serverless
Copy the code

Verify that the installation is complete

sls -v
Copy the code

The deployment of

Execute deployment instructions in project and path

The deployment of

sls deploy
Copy the code

A TWO-DIMENSIONAL code will appear in the terminal interface. You can log in by scanning wechat

Now wait a few seconds

If this figure appears, the deployment is successful

The sample access address: service-rbji0bev-1256505457.cd.apigw.tencentcs.com/release/

Address of the deployed GET interface:

  • GET /random/code
  • GET /404

The visit result shows that our reformed template project has gone up

At this point, the process from 0-1 application creation to deployment is complete

TODO

  • Complete native Node deployment of applications developed using HTTP modules
  • Complete koA project deployment
  • Explore how the terminal display two-dimensional code, the possibility of showing pictures