preface

This paper explains how I, as a front-end developer with little knowledge of servers, deployed the Node +mongodb project step by step on the server of Ali Cloud centos 7.3 and optimized the performance so that loading can be seen within one second and the content on the first screen can be seen within three seconds.

The project is built using the mainstream of the idea of front and back end separation, here only about the server environment and performance optimization.

Effect see biaochenxuying. Cn/main. HTML

1. The process

  • Develop good front-end and back-end procedures.
  • Purchase server and domain name
  • Install the required environment on the server (this project is Node and mongodb)
  • Open ports and set rules on the server
  • Use Nginx, Apache, or Tomcat to provide HTTP services or set up proxies
  • Upload project code or use the code cloud or GIhub to pull your code to the server
  • Start the Express Server
  • Optimizing page loading

2. Content details

2.1 Develop good front-end and back-end programs

Development of good front-end and back-end procedures, this is nothing to say, is the development! The development! The development! Development again!

2.2 Purchasing a Server and Domain Name

I always feel that programmers should have their own personal website, with their own domain name and server. You can test it when you’re learning something or testing a project.

Ali Cloud has a cloud wing plan for students. Ali Cloud Student Package, the original price of the entry-level cloud server is more than 1400, and it only takes 1141 years after students are certified, which is very cost-effective.

Or students, direct purchase; Is not a student, have younger brother, younger sister, can use their college student identity, purchase, very cheap and practical (I buy is the student discount package). Of course, Ali cloud server has a great discount at double 11 every year, but also very cheap, choose what configuration and price depends on their own use.

The server preinstallation environment can be CentOS or Windows Server. In order to experience and learn Linux system, I choose CentOS.

Again is the purchase of domain name Ali domain name purchase, I am also in Ali cloud purchase. Domain name is divided into international domain name and domestic domain name, international domain name is not put on record, but the domestic domain name must ICP ICP generation put on record management system, otherwise can not be used, if it is a domestic domain name, how to put on record domain name, please find their own online tutorial.

Of course, if your website is for your own use only, you don’t need to buy a domain name, because you can access the website content through the server’s public IP address.

If you have purchased a domain name, you must map the domain name to the corresponding public IP address. Otherwise, the domain name cannot be used.

3. Install the required environment on the server (this project is Node and mongodb)

3.1 Logging In to the Server

Since I am using a MacBook Pro, I directly open the MAC terminal and connect to the server through the following command line. Root is the default account name of Ali Cloud server. When connecting, you will be asked to input your password, which you set when you buy or later.

SSH [email protected] // Your server's public IP address, for example, 47.106.20.666Copy the code

As shown in figure:

For Windows, please use Putty or Xshell to log in. Please refer to this article.

Generally, you are advised to upgrade CentOS after a new server is created.

yum -y update
Copy the code

Common Linux commands

cdEnter the directorycd. Returns the previous directory ls-aView the current directory mkdir ABC Create an ABC folder mv Move or rename rm Delete a file or directoryCopy the code

3.2 installation node

To install node.js, you need to compile it through g++.

yum -y install gcc gcc-c++ autoconf
Copy the code

Jump to /usr/local/src, which is usually used to store software source code:

cd /usr/local/src
Copy the code

You can also use the SCP command to directly upload the node.js source code as it takes too long to download. Please download the latest version of the relevant source code at: Downloads.

https://nodejs.org/dist/v10.13.0/node-v10.13.0.tar.gz
Copy the code

After downloading, unzip:

The tar - XZVF node - v10.13.0. Tar. GzCopy the code

Enter the decompressed folder:

cdNode - v10.13.0Copy the code

Execute the configuration script for precompilation processing:

./configure
Copy the code

Compiling the source code, this step takes a long time, about 5 to 10 minutes:

make
Copy the code

After compiling, execute the install command to make it available system-wide:

make install
Copy the code

You are advised to install express in global mode

npm -g install express
Copy the code

Create a hyperlink or sudo node will say “Command not found”

sudo ln -s /usr/local/bin/node /usr/bin/node
sudo ln -s /usr/local/lib/node /usr/lib/node
sudo ln -s /usr/local/bin/npm /usr/bin/npm
sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf
Copy the code

View node and NPM versions with the following command:

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

At this point, node.js is basically installed.

3.2 installation mongo

Download address: mongodb download, please select the appropriate environment and version, because my server is CentOS, in fact, is Linux system, so I choose the following environment and the latest version.

mongodb :

Installation location: /usr/local/mongodb Data storage location: /home/mongodb/data Data backup location: /home/mongodb/bak Log storage location: /home/mongodb/logsCopy the code

Downloading the Installation package

> cd /usr/local> wget HTTP: / / https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.4.tgzCopy the code

Decompress the installation package and rename the mongodb folder

Tar ZXVF mongodb-linux-x86_64-4.0.4. TGZ mv mongodb-linux-x86_64-4.0.4 mongodb tar ZXVF mongodb-linux-x86_64-4.0.4Copy the code

Create the mongodb folder in the var folder, and create folders data for storing data and logs for storing logs

mkdir /var/mongodb
mkdir /var/mongodb/data
mkdir /var/mongodb/logs
Copy the code

Open the rc.local file and add the CentOS boot option:

Vim /etc/rc.d/rc.local // In vim mode, press I to insert content, and press I after inputshiftAdd :wq to save the configuration and exit.Copy the code

Add mongodb startup command to this file to make mongodb start automatically after startup:

/usr/local/mongodb/bin/mongod --dbpath=/var/mongodb/data --logpath /var/mongodb/logs/log.log -fork
Copy the code

Start the mongo

/usr/local/mongodb/bin/mongod --dbpath=/var/mongodb/data --logpath /var/mongodb/logs/log.log -fork
Copy the code

If the following information is displayed, the installation is complete and started successfully:

forked process: 18394
all output going to: /var/mongodb/logs/log.log
Copy the code

The default mongodb port number is 27017.

If you want to connect to your database with an account and password, create a database administrator, or connect directly. Create administrators and databases in mongo shell.

Switch to the admin database and create the super administrator account

use admin
db.createUser({ user: "Username".pwd:"Login password", roles:[{ role: "userAdminAnyDatabase", db: "admin"}]})Copy the code

Switch to the database you want to use, such as the TAODB database, and create an administrator account for that database

use taodb
Copy the code
db.createUser({ user: "Username".pwd:"Login password", roles:[ { role: "readWrite", db: "taodb"}] // Read/write permissions})Copy the code

Press Control + C twice to exit the Mongo shell. By now, mongodb has basically been installed and set up.

MongoDB MongoDB backup and restore MongoDB backup and restore MongoDB MongoDB backup and restore MongoDB MongoDB backup and restore MongoDB MongoDB backup and restore MongoDB

3.3 Enabling Ports on the Server and Setting Security Group Rules

If you only want static web pages, see this article to set the default home page through the cloud hosting console

But we are going to deploy the daemon, so look at the following:

What the hell are security group rules

Authorization security group rules allow or prohibit the inbound and outbound access of the public and Intranet ECS instances associated with security groups. Ali Cloud security group application case document

Port 80 is open for HyperText Transport Protocol (HTTP). You can omit port 80 when using HTTP to access an IP address or domain name

If we don’t open the appropriate ports,

For example, if our service needs to use 3000, we should open the port of 3000, otherwise we cannot access it. The same is true for other ports.

Ports are configured correctly, think you can access the public IP? Little brother, you are so naive…

There is also a firewall, if the firewall is not closed or the relevant port is not open, but also can not use the public IP to access the website content.

The security group port is the same as the security group port. For example, if the service uses port 3000, port 3000 must be opened; otherwise, the service cannot be accessed. The same is true for other ports.

For security considerations or open the firewall, only open the corresponding port best.

How to open corresponding ports? It is enough to read the following two articles, which will not be expanded here.

1. Deploy the Nodejs project on the ALIyun ESC server. Configure port 80 for the Linux operating system to access public IP addresses

2. What if “FirewallD is not running” is displayed on centos

3.4 Use Nginx, Apache, or Tomcat to provide HTTP services or set up proxies

I use Nginx, so this is just nginx. Installing nginx

1. Install Nginx on Centos7

2. Aliyun Centos7 install the Nginx server to implement reverse proxy

Start the NGNX agent

  • Go to the directory location
cd /usr/local/nginx
Copy the code
  • There is a sbin directory in the nginx directory, and the sbin directory has an nginx executable.
./nginx
Copy the code
  • Close the nginx
./nginx -s stop
Copy the code
  • restart
./nginx -s reload
Copy the code

That’s the basic usage.

Here is my nginx proxy setup:

My two projects are in /home/blog/blog-react/build/; And/home/blogs/blogs – react – admin/dist /; If your path is not this one, please change it to your path.

#user nobody;
worker_processes  1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log logs/access.log main;

    sendfile        on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout  65;

    #gzip on;

    If the port_in_redirect is off, always use the default port 80. If this command is turned on, it returns the port you are currently listening on.
    port_in_redirect off;

    The foreground displays the open service agent
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log logs/host.access.log main;
        #root /home/blog;

        location  / {
            root   /home/blog/blog-react/build/;
            index  index.html;
            try_files $uri $uri/ @router;
            autoindex on;
        }

        location @router{
            rewrite ^.*$ /index.html last;
        }

        location /api/ {
            proxy_set_header X-Real-IP $remote_addr; Proxy_pass http://47.106.136.114:3000/; } gzip on; gzip_buffers 32 4k; gzip_comp_level 6; gzip_min_length 200; gzip_types text/css text/xml application/javascript; gzip_vary on;#error_page 404 /404.html;
        # redirect server error pages to the static page /50x.html
        #error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }}# HTTPS server
    Manage the service agent opened in the background
    server {
        listen       4444;
        server_name  localhost;
        # charset koi8-r;
        # ssl_certificate cert.pem;
        # ssl_certificate_key cert.key;

        # ssl_session_cache shared:SSL:1m;
        # ssl_session_timeout 5m;

        # ssl_ciphers HIGH:! aNULL:! MD5;
        # ssl_prefer_server_ciphers on;

        location / {
            root   /home/blog/blog-react-admin/dist/;
            index  index.html index.htm;
            try_files $uri $uri/ @router;
            autoindex on;
        }
        location @router{
            rewrite ^.*$ /index.html last;
        }

        location /api/ {
            proxy_set_header X-Real-IP $remote_addr; Proxy_pass http://47.106.136.114:3000/; } gzip on; gzip_buffers 32 4k; gzip_comp_level 6; gzip_min_length 200; gzip_types text/css text/xml application/javascript; gzip_vary on; error_page 500 502 503 504 /50x.html; }}Copy the code

I have opened two agents: the service agent opened by the foreground and the service agent opened by the management background. This project is accessed through separate ports. For example: my public IP is 47.106.20.666, then can be accessed through http://47.106.20.666 can display reception, http://47.106.20.666:4444 can access management background login interface.

As for why such a configuration is written:

try_files $uri $uri/ @router;

location @router{
        rewrite ^.*$ /index.html last;
    }
Copy the code

When entering the details of the article or the front-end route changes, I refresh the browser and find that 404 appears in the browser. The resource accessed when the page is refreshed cannot be found on the server because the path set by the React-router is not a real path. So that’s set up so that you can refresh and hit the corresponding path.

When deploying single-page projects like React, Vue, etc

3.5 Upload project code, or use code cloud, GIhub to pull your code to the server

I created the code cloud account to manage the project code, because free private warehouse can be created on the code cloud. I uploaded the code locally to Gitee.com, and then entered the server to pull the code down with Git, which was very convenient.

Please refer to code Cloud (Gitee.com) help document V1.2 for details

For details about how to install Git, see CentOS 7.4 Installing Git for the system

If you don’t want to use Git for code management, use another software that can connect to the server and upload files, such as FileZilla.

3.6 Starting the Express Service

Start the Express service, I use PM2, can run permanently on the server, and the Express service does not hang on an error, and can do other operations while running.

Installation:

npm install -g pm2
Copy the code

Switch the current working directory to the Express application folder and run the pm2 command to start the Express service.

pm2 start ./bin/www
Copy the code

For example, the basic actions I take when working on a project:

cd/home/blog/blog-node pm2 start. /bin/ WWW // pm2 stop. /bin/ WWW // pm2 list //Copy the code

3.7 Page loading optimization

Let’s take a look at some configuration of nginx:

server {
        gzip on;
        gzip_buffers 32 4k;
        gzip_comp_level 6;
        gzip_min_length 200;
        gzip_types text/css text/xml application/javascript;
        gzip_vary on;
    }
Copy the code

This is the use of NGONx to open gzip, after the pro test open, compressed nearly 2/3 of the file size, originally more than 1M files, after the compression open, become about 300K.

Here are some other optimizations for React 16 load performance optimizations. See the React 16 Load performance Optimizations guide.

After a series of optimization processing, under normal network conditions, the rendering of the first screen of the page is changed from close to 5 seconds to within 3 seconds, and the loading before the rendering of the first screen is visible within 1 second.

4. Project address

My personal blog project address:

The front desk display: https://github.com/biaochenxuying/blog-react

Management background: https://github.com/biaochenxuying/blog-react-admin

The backend: https://github.com/biaochenxuying/blog-node

blog:https://github.com/biaochenxuying/blog

Series of articles on this blog system:

    1. React + Node + Express + Ant + mongodb
    1. React + Ant Design + Supports Markdown’s blog-React project documentation
    1. Blog-node project documentation based on Node + Express + mongodb
    1. How did I deploy the Node +mongodb project on the server and optimize its performance

5. The last

Friends who are interested in full-stack training can scan the qr code below to follow my public account

I will not regularly update valuable content, long-term operation.

Python, Java, Linux, Go, Node, Vue, React, javaScript