This article has documented the development and deployment process of a full-stack project with back-end separation, which I will demonstrate step by step in the form of demo. This article is a summary and share of my joy after I finally got the whole process through all kinds of pits. (I am thinking blind and I don’t know whether it is right or not.)

The Demo stack consists of React + KOA + Mongodb and related technologies.

Centos Installation Environment

I wanted to use docker to complete the whole set, but my server configuration was too low, so I timed out when I pulled the Docker image half way. I tried for a whole night without any results, but finally I had to use YUM to install it one by one. Update existing packages before installing the environment

yum update
Copy the code

Install nodeJS

Install the specified version of Node using yum

curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -
Copy the code
yum install -y nodejs
Copy the code

You can verify this after the installation is complete

node -v
Copy the code
npm -v
Copy the code

After installing Node, you can use NPM to install NVM and PM2

npm i nvm pm2 -g
Copy the code

NVM is used for node version control and PM2 is used to start node services and process daemons.

Install the mongo

  1. Create the yum source file

    Vim/etc/yum. Repos. D/mongo - org - 4.0. RepoCopy the code

    Add the following

    [mongodb-org] name=MongoDB Repository baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/7Server/mongodb-org/4.0/x86_64/ gpgcheck = 0 enabled = 1Copy the code

    Exit after saving

  2. Install the mongo

    yum -y install mongodb-org
    Copy the code

    Configure Mongodb after the installation is complete. View and modify the configuration file

    vim /etc/mongod.conf
    Copy the code

    BindIp is changed to 0.0.0.0 to support remote access. Set dbPath, directory of your choice. Fork: true indicates that the mongod is run in the background, so that the service does not need to be restarted every time. .

  3. Start the mongo

    Start Mongodb as a configuration file

    mongod --config /etc/mongod.conf
    Copy the code

    Verify that the service runs in the background after startup

    mongo
    Copy the code

Install Nginx

  1. Create the yum source file

    vim /etc/yum.repos.d/nginx.repo
    Copy the code

    Add the following

    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key
    Copy the code

    Exit after saving

  2. Install Nginx

    yum -y install nginx
    Copy the code
  3. Start the Nginx

    nginx
    Copy the code

Installation in the Local Environment

Native doesn’t have bandwidth limitations like on the server, directly on the Docker

Docker specific installation steps see www.runoob.com/docker/maco…

At the same time use the docker installation mongo, mongo – express www.runoob.com/docker/dock…

To verify Mongo-Express after installation, open http://localhost:8081/

Back-end project development

To build database

To create a database, use the command

mongo
Copy the code

Create a new demo database, create a new user set, insert a data {userName: ‘Tom ‘, age: 18}

You can also visually manipulate the database using Mongo-Express by going to http://localhost:8081/

You can see the newly created Demo database. You can also use the form in the upper right corner, enter a DataBase name, and click the Create DataBase button to create a new DataBase

Click View to View the database

You can see that the user collection has been created, and click View to View the collection

You can see the data that you just inserted. You can also visually add data by clicking the New Document button

At this point we can move the small hand of the thumbs-up, easily add delete edit data

Project initialization

Start coding when you have the data. Demo is developed using KOA and scaffolding is installed locally

npm install -g koa-generator
Copy the code

Initialize the project

koa2 -e koa-demo
Copy the code

Go to the project folder to install dependencies

npm i
Copy the code

Start the project

npm run dev
Copy the code

Open your browser http://localhost:3000/

Modify the project, and here I will directly list the modified code.

http://localhost:3000/ returns hello directly

Linked database

To operate mongodb I used Mongoose, install dependencies

npm i mongoose
Copy the code

Create /config/mongo.js and configure the link. App.js introduces configuration and initializes links

Creating a New data Model

Add the model layer

Write an interface

The scaffold uses the users route directly and adds a /list interface to access the database to obtain data

Everything is ready, test, visit http://localhost:3000/users/list

Let’s try adding a parameter

At this point, the Node service is written

Deploy the Node program to the server

Upload a file

There are many ways to upload files to the server, such as SCP, FTP, etc. I used Git here. First upload the project to Github, then go to the server and use Git to pull the remote repository files. Don’t forget to generate an SSH Key on Linux and add it to Github.

(HERE I use the manual pull code approach, there is actually a more convenient automated deployment solution, which will be demonstrated in the front-end project deployment below)

Github.com/jsliushenGi…

Here I create a new service folder in the root directory and clone the project. In this case, the project path is /root/servic/koa-demo

Start the service

Create a new database on the server, create a new collection, and insert data before starting the project

Install dependencies

npm i
Copy the code

Then start the project with pm2 (scripts in the scaffold-generated project package.json have PRD directives and start the project with Pm2)

npm run prd
Copy the code

In this case, the service listens to port 3000 and needs to open port 3000 in the security group rules of Ali Cloud. The following ports need to be opened to facilitate subsequent operations.

  • Open port 27017 for remote access to mongodb
  • Open port 8081 for remote access to Mongo-Express
  • Open port 80 for HTTP access to the server

You can access it once you have added it. The address is your server’s extranet IP plus port number

I coded it to be safe

Try accessing the interface again

The data you just added has been queried

Configure Nginx

When we access the interface, it will not be directly in the way of IP + port, generally in the way of domain name, so we need to configure Nginx, forward requests. My domain name is jsliushen.com. Add a subdomain server.jsliushen.com to access the service. For different path to service at the same time, when accessing server.jsliushen.com/demo/xxx, forwarded to the port and IP

First, add domain name resolution in Aliyun

Then edit the nginx configuration

vim /etc/nginx/nginx.conf
Copy the code

My project file is in root directory, default is no permission to access, need to set user to root. The default configuration includes include /etc/nginx/conf.d/*.conf, which means that all files with the conf suffix in the conf.d folder will take effect. Directly create the server.conf configuration file in conf.d

vim /etc/nginx/conf.d/server.conf
Copy the code

After saving the configuration, restart nginx to make the configuration take effect

nginx -s reload
Copy the code

Verify that access server.jsliushen.com/demo/users/…

Now we have an interface that runs online. At this point, the development and deployment of node back-end services are introduced.

Develop front-end projects

Initialize the project with react-create-app

yarn create react-app demo-client
cd demo-client
Copy the code

Modify the app. Js

Local start-up project

yarn start
Copy the code

After the front-end project is developed and the interface returns normally, the next step is to deploy the project to the server

Deploy the front-end project to the server

Front-end static resource deployment I use webHooks for automatic deployment

WebHooks work simply as when native push code is sent to Github, Github detects that action and requests an interface from which to pull code from the remote repository for automated deployment.

Initialize Git in the folder where you want to deploy your project, which I put in /root/website/demo-client

git init
git remote add origin [email protected]:jsliushenGit/demo-client.git
Copy the code

The project folder is still empty.

The locking file of the yarn management package used by the front-end project is yarn.lock. Therefore, yarn is also installed globally on the server

curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo

Copy the code
yum install -y yarn
Copy the code

Write the interface

The interface receives the request from Github and pulls the code from the remote repository. We put the interface in the /root/service-webhook folder

// index.js
const http = require('http');
const exec = require('child_process').exec;

http.createServer(function (request, response) {
  response.writeHead(200, {
    'Content-Type': 'application/json'
  });
  response.end();
	// Determine whether the interface is from Github and whether the behavior triggered is push
  if (request.headers['x-github-event'] && request.headers['x-github-event'= = ='push') {
    // Deployment method
    runCommand();
  }

}).listen(7777);

function runCommand() {
  exec("/root/service/webhook/deploy.sh".function (err, stdout, stderr) {
    if (err) {
      console.log('error:' + stderr);
    } else {
      console.log("stdout:"+ stdout); }}); }Copy the code

The above code should be easy to understand without going into too much detail. The following is the deploy. Sh

#! /bin/bash

WEB_PATH='/root/website/demo-client'

echo "start deployment"
Go to the project folder to deploy
cd $WEB_PATH

echo "fetching from remote..."
# pull code
git fetch --all

git reset --hard origin/master

echo "remove build"
# delete the previously built folder (the default build directory in the latest create-react-app is build)
rm -rf /build

echo "install dependencies"
# install dependencies
yarn

echo "start build"
# Start packing
yarn build

echo "done"
Copy the code

Start the service using PM2

pm2 start /root/service/webhook/index.js --name webhooks
Copy the code

The work on the server side has been basically completed. Don’t forget the 7777 port monitored by the service, and the 7777 port needs to be opened in the security group rules of Ali Cloud.

Making configuration webhooks

In making the warehouse set, adding a webhook webhooks, content, fill in the request URL address is write the address of the interface above, the server public IP + port, also can configure Nginx, become a domain name, Refer to the Deploying Node programs to the server section above. Secret is a self-defined key used for verification.

When you’re done, save the add and try it out.

Verify webhooks

Local projects push code to remote repositories while viewing PM2 logs

pm2 logs webhooks
Copy the code

After the deployment, check the project folder /website/demo-client/

The file was pulled and packed successfully.

Configure front-end Nginx

To access the front-end static files, you need to configure Nginx. Create a configuration file in /etc/nginx/conf.d, just as you configured Nginx for the back-end service.

vim /etc/nginx/conf.d/demo_client.conf
Copy the code

Set the second level domain name demo-client.jsliushen.com, and resolve the second level domain name in Alicloud domain name resolution

Hot start nginx, the configuration takes effect

nginx -s reload
Copy the code

Access to front-end projects

Open the demo-client.jsliushen.com/

At this point, the development and deployment of the front-end project is introduced.

instructions

The front-end and back-end codes of demo in this paper will always be saved on Github. The temporarily created secondary domain names and services as well as some open ports will be removed one week after this paper is sent out (2020.3.8). For security reasons, please understand.

This article is basically no rational introduction, pure step code demonstration, I hope to help you.