I am participating in the 2022 Spring Recruitment series activities – experience review, click to view the details of the activities.

One, foreword

  1. After we developed a back-end separation project, we needed to deploy the project online in order for any user to be able to access it under different conditions, so we first needed to have a server. There are many tutorials on the web that can teach you how to own your own server, which will not be described here.
  2. It is said that by the end of 21, CentOs will no longer maintain CentOs8, so let’s see which system we want to match with. This reduces the version to CentOs7).
  3. When you have your own server, you need to configure various environments to support your project to run smoothly, which is why developers say “this project works on my machine”, because “I have it configured on my machine, how do you know it doesn’t work on yours”… . Although there are relevant information on the Internet, but it is very complicated, I have wasted a lot of time because of the configuration of the environment, here is a PDF of @b station up main CodeSheep, it is really a very good configuration explanation, one-stop service, soon can configure most of the necessary environment, share with you:

Link: pan.baidu.com/s/1yKVkabO-… Extraction code: H464

Next, we will deploy the project in a basic and advanced way, starting with the manual deployment process, which is a bit more cumbersome. After all, things need to be done step by step, from easy to difficult.

Second, the practice process

Manual front-end deployment

Webpack is used here, but since the focus of this article is not on how to configure a project using WebPack, I won’t go into details, assuming you already know the relevant knowledge.

  1. The first step is to package the local project as a Dist package, which can be done with the WebPack configuration.
  2. Open theXshellTool,nginxNginx configuration file:
    • Go to [nginx installation directory] conf and modify nginx.conf.
    • For example, my installation path is/usr/local/nginx, so executevim /usr/local/nginx/conf/nginx.confAfter entering the file, pressiYou can enter edit mode to modify the file and pressescYou can exit edit mode and enter:wqSave and exit the file
// Modify the configuration as follows:
// 1. Add user root to the first line;
// 2. Locate the server{location / {}}, modify as follows
server {
  listen       80;
  server_name  localhost;

  #charset koi8-r;

  #access_log  logs/host.access.log  main;

  // Change it here:Location / {root nginx installation directory/HTML/XXX;/ / eg. Root/usr/local/nginx/HTML/dist, dist for packing after the front end of the project;index index.html index.htm; }}Copy the code

After configured nginx. Conf, save exit, restart nginx restart command: nginx installation path/sbin/nginx -s reload, for example: / usr/local/nginx/sbin/nginx -s reload

  1. Open theXftpTool to find the nginx installation path/HTML /, for example/usr/local/nginx/html/, upload the dist package to the HTML directory.

At this point, the deployment of the front-end project is complete, and you can access the IP address to see the static interface of the front-end project!

Front-end project deployment is relatively simple, as long as the packaged folder is uploaded to the server (once NGINx is configured). Let’s take a look at the deployment of the back-end project.

Manual deployment of the backend

  1. To configure Tomcat, see the PDF in 3.2 above for a tutorial
  2. Create a folder in the Tomcat installation directory to store the back-end project, named myApp. Open the Xftp tool, select the back-end file to be uploaded, and drag the file to upload
  3. Open theXshellTool, using the command line to enter myApp and install the dependencies required by the projectnpm install. Carry a mouth: can usepm2For monitoring projects, install PM2 globally firstnpm install pm2 -g, and then launch the project entry file with PM2Pm2 start Import file, you can run the back-end services.

At this point, the deployment of the back-end project is complete

Here, in fact, this should be able to successfully start the project before and after the end, and be able to run the service, but the vast majority of cases, always backfire, seems to be god, won’t make things so well, total want to let us experience a polish, and so-called “day will drop responsibility on people, also will first frustrates, harasses” is also, so always appear all sorts of strange bugs. I also met, once very nerve-racking, fortunately did not give up, and then finally solved, grit teeth stick to it. Note: Be careful when operating the server. If you delete an important running file (RM-RF), it will be unrecoverable and will lead to system failures. Be careful when running commands!

If you have successfully completed the non-automated deployment of your project, you will feel a lot of inconvenience. Here is the process of separating the project from the front end of the automatic deployment. The end result is to run the command twice in the local editor terminal: NPM run host password of the deploy server, you can separate the front and back ends of the two projects from the package to the upload server to the start project.

Automated deployment of the front-end

First of all, we need to understand a series of deployment processes of the front-end project, that is, package — log in to the server — upload the package file, so in accordance with this idea, let’s clarify the implementation process:

  1. Logical thinking
  • ① Run the script command.
  • ② Then the script reads the configuration file (including server host, port, Web directory, local directory, etc.).
  • 3.Package generates the DIST packagenpm run build;
  • ④ Connect to the server using SCP2.
  • 5.Upload the locally packaged distto/usr/local/nginx/html/
  • ⑥ Get the custom parameters of the script command, the parameters are the server host and password, and assign the value to the server configuration file (the purpose of the fourth point is to prevent the server host and password leakage in the project).
  1. Logic implementation
// Define the script command "deploy" in the scripts field of package.json file
"scripts": {
  "build": "webpack --config webpack/webpack.prod.js".// The configuration of the blogger is like this, maybe a little different from others
  "deploy": "npm run build && node ./deploy/index.js"
}

// We need to create the directory "deploy" under the root directory of the project and create the file "index.js" under "deploy". This file is used to connect to the server using SCp2, so it also contains the configuration of the server. Now start writing index.js:
/ / note: scp2 website related API usage, what need reminds is the path of the file upload need special attention, because of different tools, writing is different, the final effect is also different, for example, some tools to upload files under the directory on the server if it is found that there is no corresponding file, folder, will automatically generate but some tools not; At the same time, the uploaded file path with or without "/", also will have different effects, readers need to pay a little attention to.
// 1. Import SCP2 to connect to the server
const client = require('scp2');
// 2. Server configuration options
const server = {
  host: '', / / IP address
  port: 22./ / the port number
  username: 'root', / / user name
  password: '', / / password
  path: '/usr/local/nginx/html/dist'  // The path to the project
}
// 4. Use destruct assignment to get the following two parameters of the script command: host and password
const [ , , host, password] = process.argv;
server.host = host;
server.password = password;
// 3. Connect to the server and upload the dist package to the specified path of the serverclient.scp('dist/', { port: server.port, host: server.host, username: server.username, password: server.password, path: Server. path}, function(err) {if (err) {console.log(' file upload failed ', err)} else {console.log(' file upload succeeded '); }})Copy the code

Then run the “NPM run deploy server host server password” command to automatically deploy the front-end project

Automated back-end deployment

As with the automatic deployment of front-end projects, we also need to figure out a series of deployment processes of back-end projects, that is, to store the files to be uploaded in a separate folder — login to the server — upload files — start the project. Let’s also look at the specific implementation:

  1. Logical thinking
  • (1) Manually copy the files to a new folder named oppService.
  • ② Run the script command.
  • ③ The script reads the configuration file, including the host, port, and oppService directories of the server and the deploy.sh script.
  • ④ Use node-SSH API to connect to the server.
  • ⑤ Upload the oppService folder to the specified directory on the server.
  • Sh script, which contains the following commands to be executed after the project is uploaded: go to the oppService folder on the server to execute the deploy.sh script.
  • ⑦ Obtain the customized parameters of the NPM scripts command
  1. Logic implementation
// Also define the script command "deploy" in the scripts field of package.json file
"scripts": {
  "deploy": "node ./deploy/index.js"
}


// Create a folder "deploy" under the root directory of the project and create the file "index.js" under "deploy". To start writing index.js:
// 1. Import the Node-ssh module and prepare to call the built-in API
// const node_ssh = require('node-ssh'); Instead, you have to import it in the following form
const node_ssh = require('node-ssh').NodeSSH;
const ssh = new node_ssh();
// 6. Use destruct assignment to get the following two parameters of the script command: host and password, and store them in config
const [ , , host, password] = process.argv;
// 2. Server configuration options
const config = {
  path: {
    localPath: 'oppService/',
    romotePath: '/usr/local/apache-tomcat8.571./Online-programming-platform_service',
  },
  romote: {
    host: '',
    port: 22,
    username: 'root',
    password: ''
  }
}
function uploadFile() {
  // 3. Connect to the server
  ssh.connect(config.romote)
  .then(() => {
    // 4. Upload the dist package to the specified path of the server
    ssh.putDirectory(config.path.localPath, config.path.romotePath)
    .then(() => {
      // 5. Run the script to backup the server after the file is uploadedssh.execCommand('sh deploy.sh', { cwd: config.path.romotePath }) .then((res) => { if (! res.stderr) { process.exit(0); }})}). The catch (err = > {the console. The log (err)})}). The catch (err = > {the console. The log (' server connection failure!!!!! ') }) } uploadFile();// Write the deploy.sh script#! Pm2 stop SRC /app.ts # pm2 stop SRC /app.ts File ='node_modules' if [-e $file]; Then rm -rf $file NPM cache clean --force fi #8080If the port is occupied, kill is used to prevent the project from failing to start port=8080
pid=$(netstat -nlp | grep :$port | awk '{print $7}' | awk -F"/" '{ print $1 }')
if [ -n "$pid" ]; then
  kill 9 -$pid; Fi # ⑤ Restart pm2 pm2 start. / SRC /appCopy the code

Third, summary thinking

  1. After implemented the project deployment automation, the deployment process less tedious, immediately brought the efficiency, a command will fix everything, but I feel that there are optimal space, such as the back-end programs require prior to upload files pulled out, after that every time we write the code have to update the file again, is not very convenient, This problem will be perfected later (= ω ̄=). If you think you have a good solution or something that could be improved, feel free to post it in the comments section. Thank you in advance

I will come back to improve it when I have time

  1. From being ignorant of the server, to mastering the deployment of online projects, to skilled operation of the command line, and to exercise the ability to solve problems, these are all the benefits brought by the blogger in completing the online deployment of the front and back end separation project, and there is no doubt that the harvest is quite abundant. Implementation process is not easy, however, sometimes a bug a card is two or three days (or lack of ability after all. T ^ T), waste a lot of time, but insists there will always be, at least the ability to troubleshoot problems more or less can be improved, sincerely hope that readers will complete deployment of the project, direct customs clearance 【 monsters (bug) leave quickly, Get out of here.

The above ^_^