First, write first

Project deployment is an essential part of web development, and every qualified front-end developer should know something about it, not just ignore it. Admittedly, going through the entire deployment process for the first time is fraught with twists and turns, but these lessons are indispensable and irreplaceable for understanding the entire process and even the details of how to interact with a web address in a browser. In this dog-eat-dog world, only weapons sharp enough to stand up against fierce enemies.

Around the beginning of the year, I finished my first website as a beginner. In retrospect, I can still vaguely feel the headaches that accompanied me at the time — the obstacles that prevented me from buying a server to being able to open the site through a browser. On second thought, perhaps it is these obstacles that drive me forward. Today, 2020 is also coming to an end, their progress is obvious. Especially when it comes to the bugs that are difficult to solve, I will no longer spit out bitter complaints, but calmly deal with them. In my opinion, the ability to correctly deal with bugs is also a kind of ability, which is of great significance for improving programming experience and personal programming level.

I recently launched my own blog, Freesism, so I went over the deployment process again, wrote it down and shared it. This is the second time for me to write, hoping to more or less help those in need and encourage myself to be more diligent and hardworking in the future.

Tips: The front-end technology stack used by Freesism is Vue, server Nestjs and database MySQL. This article shows you how to package a Vue project locally, deploy it to a remote server that can be accessed by entering an IP address (domain name address) into a browser, and deploy the Nestjs service to provide the data interface. Due to my limited level, the following content is only shared as personal experience, if there is any mistake, please correct in time, thank you!

Practice is the sole criterion for testing truth.

Second, preparation

The following conditions are required:

  • Have a server.
  • Choose the appropriate tools to connect to and manipulate the remote server.
  • A persistent heart and industrious hands.

How to choose and buy a server will not be discussed in this article, there are many manufacturers on the market, choose suitable for their own can. I am currently using the Aliyun lightweight server I bought at school, which is only for reference here. In addition, it is recommended to buy a domain name you want and record and resolve the domain name according to your needs.

As for the server system, I choose Ubuntu 18.4. There are similar systems in the market, so I will not discuss them in depth here. If you are interested, please do your own research. Personal tools commonly used to connect and operate Remote servers mainly include Xshell, Xftp, WinSCP, remote-SSH (VS-Code plug-in). There are many other tools in the market, just choose your favorite. This section uses Xshell 6 to demonstrate the operation.

All ready, let’s go!

Initialization

Step 1: Connect to the remote server.

Log in to the server console and copy the public IP address (you can also use the bound domain name instead of the IP address).

Use Xshell 6 to establish the connection.

Click connect and enter the user name (the initial user name is usually root) and password as prompted. If the following interface appears, the connection is successful.

PS: You are advised not to use the root account for subsequent operations on the remote server. For demonstration purposes, you are advised to create a subuser. For details about how to create a subuser and authorize a subuser, you are advised to search by yourself. If a subuser is not authorized, a message may be displayed indicating insufficient permissions in subsequent operations. In this case, you need to add sudo before the command to enhance your permissions.

Step 2: Update and install the required packages.

Enter the following commands in sequence:

Sudo apt-get install nodejs sudo apt-get install nodejs sudo apt-get install nodejs sudo Apt-get install NPM -y # install NPM sudo NPM install n -g # install nodeJs latest # Update nodejs to latest version, optional Sudo NPM install pm2 -g # Install pm2, the node process management tool, which is used for persistent running and monitoring Nestjs serverCopy the code

Step 3: Install Nginx.

Sudo apt-get install nginx -y # install nginx serverCopy the code

After the preceding operations are complete, enter the public IP address or bound domain name in the browser. If the following page is displayed, the Nginx service is successfully started.

Step 4: Install MySQL.

Sudo apt-get install mysql-server sudo systemctl status mysql.service If active (running) is displayed, the function is enabledCopy the code

Log in with the default user:

Mysql -u user -p "mysql -u user -p" mysql -u user -p "mysql -u user -p" mysql -u user -p" Password sudo service mysql restart mysql -u root -pCopy the code

After login, enter the following Mysql statement to change the password of user root:

update mysql.user set authentication_string=password('password') where user='root' and Host ='localhost';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
flush privileges;
quit;
Copy the code

To facilitate debugging and the unification of the local database and the remote server database, here is how to connect to the Mysql service remotely through SQLyog. Check whether port 3306 is enabled on the server:

Netstat - an | grep 3306 # check whether open port 3306Copy the code

Open port 3306:

CD /etc/mysql.conf. d # go to the mysql configuration directory vim mysqld. CNF #Copy the code

Press Esc, Shift + :, enter wq, and press Enter to save and exit. Please refer to the detailed operation of vim editor for further information.

After the port is enabled, access Mysql again and grant all remote connection permissions to the root user.

GRANT ALL PRIVILEGES ON*. *TO 'root'@The '%'IDENTIFIED BY 'password' WITH GRANT OPTION;

FLUSH PRIVILEGES; # Refresh permission data

exit; 
Copy the code
Sudo service mysql restartCopy the code

Establish a remote connection using SQLyog:

Once the connection is successful, you can directly manipulate the remote Mysql service locally using visual tools. At this point, initialization is complete.

Iv. Automated deployment

Traditionally, we would use a transport tool like Xftp to copy packaged resource files to a remote server. Now, there are enough automation options that we can choose from, and automation saves us a lot of operations when we need to update resources frequently. Git Hooks, which allow you to automate deployment locally with just a few Git commands. The specific operation steps are as follows:

Step 1: Install Git.

sudo apt-get install git -y
Copy the code

Step 2: Initialize the Git repository.

Git init. Git --bareCopy the code

Step 3: Add the post-receive hook.

Create a new post-receive file vim post-receive # Edit the file via vimCopy the code

Press I for edit mode and write the following code:

#! /bin/bash 
#Define the file to be executed using bashecho 'remote server: receive code... '#The output above appears when we are in the local push code

cd /website 
#Switch to a directory for storing code, optional

git --git-dir=/opt/website.git --work-tree=/website checkout master -f
#Specify the Git file and the branch and directory to checkout from

#Enter the front end project, install and packagecd /website/web echo 'web running npm install... ' npm install \ && npm run build \ && echo 'web builded.'
#Go to the server project, build and runcd /website/server echo 'server running npm install... ' npm install \ && npm run build \ && echo 'server builded.' \ && npm run pm2 \ && echo 'done.'Copy the code

After saving and exiting, type the following code on the command line to set the owner of the post-receive file as user root.

sudo chmod +x post-receive
Copy the code

Step 4: Add remote records to the local project.

Git remote add prod SSH ://root@[public IP address or domain name of the remote server]/opt/websiteCopy the code

After the configuration is successful, the local code can be pushed to the remote server through git push prod command, and the server will perform a series of operations such as packaging and running according to the post-receive configuration file.

PS: NPM install directive If the installation is too slow, taobao image can be configured, how to configure please consult yourself. The instructions in the post-receive file can be written based on the actual project situation, such as NPM run pm2 above, which actually executes pm2 startOrRestart pm2. Json to run and monitor the Nestjs service. Json is the PM2 configuration file. For details, see the PM2 documentation – JSON Configuration. You can also run the pm2 command.

5. Modify Nginx configuration

The power of Nginx is undeniable, and probably doesn’t need much introduction. As a front end who has never touched it, it can feel strange and even intimidating. In my own experience, when I first looked at its configuration file, I had no idea what was going on. However, after a few do-it-yourself configurations, the fear of it gradually disappeared, which also made me understand a truth – all things are difficult before they are easy.

More not to say, directly on the configuration steps.

Step 1: Create a configuration file in /etc/nginx/sites-enabled.

The site-enabled directory stores the current enabled site configuration. You can create multiple virtual hosts as required. For example, my main domain name – www.striveforus.com/ – points to my blog site.

CD /etc/nginx/sites-enabled touch striveforus.com.conf # create a site configuration file, name it yourself, remember to add conf suffix vim striveforus.com.conf # edit the fileCopy the code

Press I to write the following code:

server {
    listen      80; # listen on port 80
    listen[: :] :80; # IPv format
    server_name www.striveforus.com; # To match a domain name, you can configure multiple or subdomain names.
    
    # root resource address, I put the front-end project packaged resource file in the server directory, as a Nginx static resource.
    This can be modified according to your own needs.
    root  /website/server/mobile/;
    index /index.html; The root file under the root resource address
	
    Front-end data interface reverse proxy configuration, front-end AXIOS configuration baseURL is /web/ API
    # Match starts with /web/ API /, reverse proxy to Nestjs server (make sure the running port is the same as below) processing
    location /web/api/ {
        proxy_pass http://127.0.0.1:3000/; 
    }

    # generic matching
    location / {
        Refresh 404 after resolving SPA redirect route
        try_files$uri $uri/ /index.html; }}Copy the code

After saving and exiting, restart Nginx service:

service nginx reload
Copy the code

Then open your browser and type in the url:

The basic configuration above is ok, but the actual requirements are often more than that, such as setting subdomain names, setting HTTP headers, doing jumps, redirects, enabling gzip compression, etc., all need to be added.

Step 2: Add the configuration as required.

For example, now I have a requirement to add an admin background for the site, but I don’t want to access it under www.striveforus.com/xxx, but through a subdomain like admin.striveforus.com, And the front-end packaged resources are static resources under the Nestjs server. My solution is as follows:

Add a record under the master domain name.

Then add the VM configuration file in the site-enabled directory.

Touch admin.striveforus.com.conf # new vim admin.striveforus.com.conf # editorCopy the code

Write the following code:

server {
    listen      80; 
    listen[: :] :80;
    server_name admin.striveforus.com;

    location / {
        Make sure the Nestjs service is on port 3001
        proxy_passhttp://127.0.0.1:3001/; }}Copy the code

Save exit and restart Nginx service:

service nginx reload
Copy the code

Open browser test:

The subdomain name was configured successfully. There are many other configurations, which I won’t show here, but can be found with a bit of careful searching. If you are too lazy to do your own configuration, here I recommend an automatic generation of Nginx configuration website – NGINXConfig, according to their own needs to generate configuration files, very convenient and fast.

Step 3: Upgrade HTTPS.

Why you want to upgrade HTTPS and its benefits will not be explained here, please find out for yourself. The key to upgrading HTTPS is to get a certificate, usually for a fee, but some are free and can be found online. I personally use Let’s Encrypt’s free certificate, and I recommend it to you because it’s really convenient. Just select the server and system and follow the installation steps below.

Six, the summary

This article shares the entire process of deploying a personal front-end project online, including the following points:

  1. How to connect to a remote server, install and update required toolkits.
  2. How to automate using Git Hooks
  3. Modify the Nginx configuration as required and upgrade HTTPS.

Welcome to visit my blog, Freesism, and communicate with me.

Well, that’s all for this article.

Thanks for reading and welcome to share!