Author: Lu Cheng

What do I do when I encounter front-end deployment problems? How to configure nginx, port, HTTPS domain name, react/ Vue project deployment, reverse proxy, please read carefully. This article is easy to understand, easy to operate, and aims to inspire others. If it helps you, please give it a thumbs up.

preface

Front-end deployment is about getting the front-end code running in a server environment. And front-end daily work, mainly business code development, resource reference, front-end routing configuration. As for deployment, more operation and maintenance personnel do not have much contact with operation. However, in real projects, there are often a variety of problems as soon as we deploy to these environments. If we have relevant theoretical and practical experience in deployment, it will be easier to locate problems and improve online efficiency.

background

When you buy a server and plan for the future, you plan to build a platform. The question is, how to deploy the front-end project…

Several expected goals:

  • 1. Web site (SEO) based on nextJS front-end Web service, port 18001(modifiable). Create the nextjs official example github.com/zeit/next.j…

  • 2. API service based on the front-end NODEJS service of KOA, port 18000(modifiable). Via KOA scaffolding github.com/17koa/koa2-… create

  • 3. Static Web Project 1- Vue-based front-end single-page static resource project/VUe-app. Use vue-CLI to create cli.vuejs.org/zh/

  • Static Web project 2- Static resource project/React -app based on react/typescript. Create github.com/ant-design/ from create-react-app-antd github.com/ant-design/…

  • 5. Public static resource images, CSS, JS, etc. /static

directory

Starting from scratch, follow the list below

  • 1. Server classification
  • 2. Lightweight and powerful Nginx
  • 3. Front-end service management tool – PM2
  • 4. Solve cross-domain “problems”
  • 5.☆ Deploy react/ Vue single-page static projects
  • 6. Implement HTTPS
  • 7. Continuous Integration CI- Automated deployment

1. Server classification

1.1 Application Server

Focus on dynamic resources, parsing code written in high-level development languages. Front-end services are usually built on nodeJS, which parses JavaScript language

  • JAVA: Tomcat, resin, Jboss, WebLogic, etc
  • PHP, Apache, and so on
  • The.net: IIS, etc
  • Nodejs: Express, KOA, eggJS, etc

1.2 Gateway Server

Focus on static resources, proxy forwarding, load balancing, etc

  • Nginx, Tengine, etc

2. Lightweight and powerful Nginx

Nginx has many features, some of which are commonly used in the front end, and other features have been proved by major Internet companies through a lot of practice. Nginx configuration is mainly about configuring nginx.conf and changing the reload to make the configuration take effect. For details on nginx download and tutorial, please refer to the official website. Nginx mainly modifies configuration files and takes effect.

2.1 introduction

2.1.1 Common Front-end features

  • Domain name binding
  • Static resource
  • The reverse proxy
  • Support HTTPS
  • cross-platform

2.1.2 Other Features

  • Load balancing and high concurrency

2.1.5 Nginx Download and Directory Description

Nginx official website: nginx.org/

Nginx modifies the conf/nginx.conf configuration file and restarts the nginx program to implement server functions.

Exe -s reload // Linux/MAC nginx -s reload // ps Forcibly end the nginx.exe process in Windows using the taskkill /f command /t /im nginx.exeCopy the code

2.2 Actual Configuration

2.2.1 Environment Preparation

  • Download the latest nginx package from nginx.org. Decompress the package for Windows, Linux, or MAC
  • In Windows, create a directory C :/server for the root directory on drive C. Linux/MAC can be created in a directory such as root directory /server

2.2.2 Static Resources

First, we will implement static resource configuration of JS, PNG images and CSS resources. Create static folder in server folder, create js folder, IMG folder, CSS folder respectively, and place the test file content in the corresponding format in the corresponding folder. The final access path and effect are as follows:

/static/js/js.js
/static/img/img.png
/static/css/css.css
Copy the code

2.2.3 Configuring Static Resources for Nginx

Conf /nginx.conf file in nginx folder corresponds to the following configuration. After configuration, you need to restart nginx, including how to restart the process, end the process and start it again or reload.

{# nginx listen 80; # nginx listen 80; # nginx localhost server_name localhost {#root C:/server/; alias C:/server/static/; autoindex on; #autoindex on; }}Copy the code

2.2.4 Directory Index

If autoIndex on is configured, directory indexes are displayed if directories are accessed. 403 Forbidden is displayed if autoIndex on is disabled. In order to prevent the server from being detected, the index directory is closed.

Enable index effect

Turn off index effects

2.2.5 Attachment: Nginx static site

Configure three static Web sites as standby. The configuration method is very simple, C:/server create two folders, each with an index. HTML file immediately. Conf add the following configuration and restart nginx to take effect.

server { listen 10001; server_name localhost; root C:/server/siteA; index index.html index.htm; } server { listen 10002; server_name localhost; root C:/server/siteB; index index.html index.htm; } server { listen 10003; server_name localhost; root C:/server/siteB; index index.html index.htm; location / { add_header X-Frame-Options SAMEORIGIN; }}Copy the code

At this point, task 5 static resource task is completed. Congratulations on your ability to use Nginx to build static Web sites and static file services. You can explore other configurations on your own.

3 Deploy the front-end service – PM2

Front-end services – that is, front-end services such as Web services that can be accessed independently based on the NodeJS platform. Such as NextJS, Express, KOA, EGGJS and other front-end application servers.

What is the pm2

If you have multiple services, you have to open multiple services. In a server environment, you only have one bash port and you have to run the nodeJS service in the background. As well as managing the suspension, restart, and destruction of various NodeJS services, we needed software that could manage them. Pm2 came into being.

Pm2 tool: Change nodeJS service into background service, unified management (often used in server environment, console command environment)

See the pm2 www.npmjs.com/package/pm2 official document, pm2. Keymetrics. IO/docs/usage /…

The installation

NPM install pm2 - gCopy the code

Common commands

  • Pm2 start pm2. Json # Start the process according to the pm2
  • Pm2 list, pM2 status # Lists all current PM2 management lists
  • Pm2 stop 0 # Stop the specified service
  • Pm2 delete 0 # Delete the specified service
  • Pm2 restart 0 restart the specified service

In actual combat

We started nodeJS service of NextJS and KOA2 according to the above initial official project (before we executed NPM run start, local simulation can be directly started first), now if pM2 transformation is needed

First look at the running effect:

1. Nodejs service based on Nextjs: 127.0.0.1:12111

2. Koa2-based nodeJS service: 127.0.0.1:18000

3. Pm2 list Lists all node services hosted by PM2

configuration

The pm2 command is executed directly from start.bat/start.sh. Finally, pM2 is given hosting for indirect execution of the command to NPM start

The PM2 in Windows has some problems. You need to run the NPM command in indirect mode

// 1. Add start.bat/start.sh to the root directory of the koa/nextjs project, which contains the pm2 command pm2 start file.config. js // 2. Create the file.config.js configuration file, as discussed below. You may refer to other parameters in detail pm2 website to check the specific configuration. https://pm2.keymetrics.io/docs/usage/application-declaration/ module. Exports = {apps: [{name: 'MyKoa', script: 'start.js', args: 'one two', instances: 1, autorestart: true, watch: false, max_memory_restart: '1G', env: { NODE_ENV: 'development' }, env_production: { NODE_ENV: 'production' } }] }; // 3. Create start.js const CMD = require('node-cmd'); cmd.run('npm run start'); {"start": "node bin/development.js",} {"start": "node bin/development.js",}Copy the code

At this point, you have two front-end Node services running locally. 50% of tasks 1 and 2 are completed.

4. Solve cross-domain “problems”

4.1 Cross-Domain: A normal security policy

With both of our nodes started, you would immediately want nextJS’s fetch to request koA’s API service, and the result is cross-domain.

Scenario 1. Same-origin restrictions such as XMLHttpRequest and FETCH

Browser security Access to different ports and domain names is not allowed by default for security reasons. There would be no security if everyone could call each other.

Scenario 2 iframe cross-domain reference problem

For security purposes, the Response header of a page’s HTTP request is set to X-frame-options: SameOrigin to prevent the page from being embedded in other sites.

4.2 Nginx Solution – Reverse proxy

4.2.1 What is a Reverse proxy

In a word: the client requests the server, the server receives and forwards the content to other servers, and then passes it to the client.

In Reverse Proxy mode, a Proxy server receives Internet connection requests, forwards the requests to the Intranet server, and returns the results to the Internet client. In this case, the proxy server acts as a reverse proxy server.

Forward proxy: a server located between the client and the origin server. In order to get content from the origin server, the client sends a request to the proxy and specifies the destination (the origin server). The proxy then forwards the request to the origin server and returns the content to the client.

4.2.2 First look at the expected effect of nginx

Data is returned when localhost access/API /test/list is successfully forwarded to koA service (127.0.0.1:12111)

4.2.3 Configuring a Reverse proxy on nginx

# 1. Web Server with nextJS home page for SEO optimization. Access all preferentially forwarded to nextJS service location / {proxy_pass http://127.0.0.1:12111/; proxy_redirect off; proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Via "nginx"; } # 2. The location/forwarding/API request to front-end koa server API {proxy_pass http://127.0.0.1:18000/api; proxy_redirect off; proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Via "nginx"; }Copy the code

4.3 Iframe Solution across domains

Iframe across domains typically sets the Response header via the server. It is divided into the old version browser and the new version browser. The old version is X-frame-options. The new version is Content-security-policy. For reference: developer.mozilla.org/en-US/docs/…

In nginx, you can specify the domain name that can be accessed by the iframe

# Be embedded with iframe Web Settings
server {    
    listen       10004;
    server_name  localhost;
    root C:/server/siteB;
    index  index.html index.htm;
    location / {
      # the old version
      add_header X-Frame-Options "ALLOW-FROM http://localhost";
      The new version uses CSP
      # add_header content-security-policy "frame-rooted 'self 'http://localhost";}}Copy the code

4.4 HTTP Headers cross domains

It is typically a mock Server at development time, or a domain name that allows cross-domains. This way, we can access the mock data directly

☆5. Deploy react/ Vue single-page static projects

This section is a must-have deployment for React/Vue developers, because your code will always be released and you’ll be able to quickly identify problems.

5.1 Core Issues of Single-Page Applications

Deployment of single page application project our core thinking: server-side routing and static single page application routing conversion process

5.2 Configuring single-page Applications for NGINx

We analyze: when accessing the URL, first visit the Nginx server, nginx route decision after the front-end route hosting. We arrive at the following configuration: all routes under the subpath accessing the static resource are forwarded to the index.html file of the static resource. Translate back-end routes into front-end routes.

Create-react-app static project location /react-app {# path alias C:/server/create-react-app-antd/build; # default index index. Try_files $uri $uri/ /react-app/index.html; } # 2. Vue static project location /vue-app {alias C:/server/vueapp/build; index index.html; try_files $uri $uri/ /vue-app/index.html; }Copy the code

Fault 1: The original project cannot be accessed after the configuration is complete. A resource error occurs

Vue-cli project configuration

First of all, if you install dependencies directly from the vue official website command, run the NPM run build, the configuration will be error.

Cause: The CSS/JS resource reference path is not referenced. In solution 1, change it to a relative path

Recompile after modification, access is successful

Configure the React Project

By default, the create-react-app-antd project NPM run build is configured and resources cannot be accessed. The reason is that projects are all absolute paths to access resources.

The React project reads the package.json homepage entry as the root path due to the scaffolding configuration

Repackage and compile after normal access. A slight change was made here to add a route redirect to test static resource routing.

Question 2: I went online. Click on the react project homepagehttp://localhost/react-app/Click the link to jumphttp://localhost/react-app/testYes, but I refresh the page to report nginx404. (many friends have appeared after the release of this situation obviously default can click, refresh the page can not open the 404)

Child route 404 after page refresh

Why refresh error?

If you think about it for a moment, the root cause is the conversion problem of the front and back end routes. Remember the important sentence in the configuration line above: try_files, which means that the server can’t find the files and you have to tell what to do about it. This is where the problem is located: try_filesuri/ /react-app/index.html; This exception handling, if not added, will cause the file to be inaccessible to the refresh. Review the configuration: when unreachable, it is forwarded to the following index.html page, which seamlessly connects to the front-end route. Problem solved.

location /react-app { alias C:/server/create-react-app-antd/build; index index.html; Try_files $uri $uri/ /react-app/index.html; }Copy the code

At this point, you have the ability to apply a single page project, determine resource access paths, and troubleshoot classic problems like deploying a page refresh report 404. The static subproject of task 3 and 4 React/Vue is successfully deployed.

6 the HTTPS access

At this point, the above several application systems have been fully operational. But ISN’t HTTP insecure? I need HTTPS to make my website safe to access.

6.1 Key Elements of SSL Certificate-based HTTPS Access

  • Applying for a Certificate and Key (OpenSSL Tool)
  • Configure nginx

In the local environment, you can use the command line tool to generate the secret key and certificate to test HTTPS

Nginx local HTTPS secret key reference documents: www.cnblogs.com/isylar/p/10…

The HTTPS access port number changes to 443

The configuration of nginx is as follows: The key is the generation of pem certificates and keys. It can be generated locally by following the above documentation, and there are many tutorials on how to generate HTTPS certificate keys online.

 server {
        listen 443 ssl;
        server_name localhost;
        index index.html index.htm index.php;
        root  C:/lc/server;
        # Pem certificate path
        ssl_certificate  C:/lc/work/proj/https/server/server.pem;
        # Pem certificate pathssl_certificate_key C:/lc/work/proj/https/server/server.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:! NULL:! aNULL:! MD5:! ADH:! RC4; Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; The location / {... }}Copy the code

Symptom: The browser displays an insecure connection message after HTTPS access is configured on the local PC

Answer: Since browser HTTPS is a certificate that requires a valid CA method, our own configuration is not through a certificate authority. Click to continue or you can access it locally.

How do I force an HTTP request to become an HTTPS request

Rewrite all requests to HTTPS after port access

server {
      listen 80;
      server_name  localhost;
      # force HTTPS
      rewrite ^(.*)$ https://$hostThe $1 permanent;
}

Copy the code

7. Continuous Integration CI- Automated deployment

7.1 Core Ideas

  • Ability to execute server-side scripts
  • Use the Web UI to facilitate operations
  • Support for trigger builds such as Git Web hooks

7.2 Common Software

  • Jenkins jenkins.io/zh/

7.3 Write a script for Automatic code update and automatic package

Build. sh and build.bat in C:/server/create-react-app-antd

build.bat

echo start build...
echo running step 1.git pull
git pull
echo running step 2.npm run build
npm run build
Copy the code

build.sh

#! /usr/bin/env bash echo start build... echo running step 1.git pull git pull echo running step 2.npm run build npm run buildCopy the code

finishing

Can see here, really thank you for your patience, is there a kind of enlightened, the original front-end deployment is enough. With these, we can no longer be a blind spot in the future front-end on-line deployment, but also quickly locate problems. At the end of the sentence: if I help you, please give me a thumbs-up, thank you (90-degree bow).

For more shared articles from skFeTeam, click herehere, thank you ~