Background service building and nginx server

beifengtz 2020-11-13 01:42:31
background service building nginx server

This blog mainly records how I usually build the server , From sophomore to the server , After a year, I stepped on a lot of pits , Now I've found some ways , Of course, I'm sure my approach is not the best , Study ing, Welcome friends to communicate with me .

One port, one service

When I was a freshman, I mainly used Apache and Tomcat Two kinds of servers , At that time, I didn't know much about linux operating system ( The server is best to use linux), So it's used Windows Server 2016. I remember using PHP When making a website , It's using wampserver This software , And it can only run on windows In the environment . Run after installing the software apache That's all right. , If you want to modify the port, you just need to configure the corresponding configuration file .

Join in WingStudio And then I turned to Java, Usually used more is Tomcat 了 , This is very simple , take java programmatic war Inclusive Tomcat Of webapp Under the table of contents , And then in its bin Run in directory startup.bat That's all right. (linux function, If you want to modify the access port, you just need to conf/server.xml Find the corresponding configuration in it .

A simple web Service is best understood , It should also be easy for beginners to accept .
 Insert picture description here

Multiple ports, multiple services

In fact, this is to build several simple services , The main point here is to introduce the back nginx and docker Some advantages of .
If I now have five services to put on the server , Without using any other tools , Then I need to start five services on the server , And open a port for each service . It's a waste of resources , But it's also something I've tried , How do you know the advantages and disadvantages of it if you haven't tried it ? Let's take a look at a diagram of it :
 Insert picture description here

Multiple services on the same port

When we have a lot of services to mount on the server , But I want to access different services through one port , And on a server ( With Tomcat For example ) Under the premise of , You can put multiple services under the server , And do port mapping ( If it is 8080 port Tomcat Bring their own , If it is another port, you need to use the server.xml Middle configuration , This configuration thief is angry , Personal test !!), It's also the way I've used most before . Its structure is as follows :
 Insert picture description here

It's easy to run into a problem with this approach , It's also something I've met before , Namely Tomcat Out of memory !!! At that time, I was very confused when I saw this mistake , Try to give Tomcat Allocate more memory , Although this can solve the problem , But there are still some problems , such as Tomcat The server is under too much pressure , When several services are running at the same time , If your service is still big ,Tomcat Probably GG, In order to solve this problem, we can use the method of consuming operating system resource space to enhance the performance of your service .

Use nginx The server

If you have two services to go online now , There is only one registered domain name , A server host , I have obsessive-compulsive disorder , Don't like to visit with port when accessing , In order to reduce Tomcat Pressure can't be used on it “ Multiple services on the same port ” Methods , So in this case , One Tomcat The server can't meet the demand . This is also the case when I used to configure the server , Through the introduction of elder martial brother Nginx The server can do reverse proxy , That's great , So I tried to learn .

nginx brief introduction

First copy Let's talk about Baidu Encyclopedia nginx Introduction to

Nginx (engine x) Is a high-performance HTTP And reverse proxy services , Also a IMAP/POP3/SMTP service .Nginx It was by igor · Mr. Seshoyev was the second most visited city in Russia Site ( ru :Рамблер) Developed , The first public version 0.1.0 Published on 2004 year 10 month 4 Japan .

Nginx It's a lightweight model Web The server / Reverse proxy server and email (IMAP/POP3) proxy server , And in one BSD-like Issue under agreement . It is characterized by less memory , Strong concurrency , in fact nginx The concurrency of, and indeed in the same type of web server performance better , Used in mainland China nginx Website users have : Baidu 、 JD.COM 、 Sina 、 NetEase 、 tencent 、 Taobao, etc. .

If you want to make children's shoes for service operation and maintenance nginx It is necessary to learn , But as a developer, it may be said that you don't have to learn deeply , But the basic principle and application still need to master , Next, I'll talk about my understanding of nginx The understanding of the .

From my usual application ,nginx The biggest advantage is Load balancing Reverse proxy and Static file distribution , Let's talk about how I usually use it , There must be many shortcomings , I hope you can raise some .

nginx Reverse proxy

What is reverse proxy

Reverse proxy (Reverse Proxy) Method is to accept as a proxy server Internet Connection request on , Then forward the request to the server on the internal network ; And return the results from the server to the Internet Clients requesting connections on , At this time, the proxy server is represented as a server . The usual proxy server , Only used to proxy internal network pairs Internet Connection request for , The client must specify a proxy server , And send it directly to Web On the server http The request is sent to the proxy server . When a proxy server can proxy hosts on external networks , When accessing the intranet , This way of proxy service is called reverse proxy service .
 Insert picture description here

nginx How reverse agents work

( This part is transferred from

There are usually two models of reverse proxy servers , It can act as a stand in for a content server , It can also be used as a load balancer for content server clusters .

One 、 Act as a stand in for the content server

If your content server has sensitive information that must be kept safe , Like the credit card number database , A proxy server can be set up outside the firewall as a stand in for the content server . When an external client tries to access the content server , It will be sent to the proxy server . The actual content is on the content server , Secure inside the firewall . The proxy server is outside the firewall , It looks like a content server to the client .

When a client makes a request to the site , The request will go to the proxy server . then , The proxy server passes through a specific path in the firewall , Send the client's request to the content server . The content server sends the results back to the proxy server through this channel . The proxy server sends the retrieved information to the client , It's like the proxy server is the actual content server ( See chart 2). If the content server returns an error message , The proxy server intercepts the message first and changes any of the URL, And then send the message to the client . This prevents external clients from getting redirects from the internal content server URL.

such , Proxy servers provide another barrier between secure databases and possible malicious attacks . In contrast to having access to the entire database , Even if it's a fluke attack , At best, the perpetrator is limited to accessing the information involved in a single transaction . Unauthorized users cannot access the real content server , Because firewall access only allows proxy server access .

 Insert picture description here
Firewall router can be configured , Make it only allow specific servers on a specific port ( In this case, the proxy server on the port to which it is assigned ) Have access through the firewall , No other machines are allowed in and out of .

Two 、 As a load balancer for content servers

Multiple proxy servers can be used within an organization to balance the various Web Network load between servers . In this model , You can take advantage of the caching features of proxy servers , Create a server pool for load balancing . here , The proxy server can be located on either side of the firewall . If Web The server receives a lot of requests every day , You can use a proxy server to share Web Server load and improve network access efficiency .

For requests from clients to the real server , The proxy server acts as an intermediary mediator . The proxy server caches the requested document . If there is more than one proxy server ,DNS May adopt “ Circular repetition ” Select it IP Address , Randomly route requests . The client uses the same... Every time URL, But the route taken by the request may go through a different proxy server every time .

Multiple proxy servers can be used to process requests to a high-volume content server , The benefit of this is that the content server can handle a higher load , And more efficient than working alone . During initial start-up , The proxy server retrieves the document from the content server for the first time , thereafter , The number of requests to the content server will drop dramatically .
 Insert picture description here

nginx To configure

If there are multiple services , It is not recommended to go directly to nginx.conf Configure your service under this configuration file , Best in nginx In the root directory conf.d Add your profile to the file , Of course, we need it here conf.d All configuration files under file are imported to nginx.conf In the middle . stay nginx.conf in http Add this sentence to the configuration

 include /etc/nginx/conf.d/*.conf;

For example, I have two services which are VR360 and blog, So I just need to be in conf.d Create two files in VR360.conf and blog.conf That's all right. , The configuration of each service is placed in its own configuration file , Easy to manage , And it's not easy to make mistakes . The following is the introduction of the configuration template in the blog of the big guy

server {
listen 80;
root /root/nmapp2_venv;
index index.html;
server_name server;
location / {
#if (!-e $request_filename) {
# rewrite ^/(.*)$ /$1 last;
# Here you configure which service to forward to
proxy_pass http://localhost:8080/;
#Proxy Settings
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
location ~ /index\.py {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://tornado;

nginx Load balancing

More and more visits to the website , The service mode of the server has to be upgraded accordingly , For example, separate the database server 、 Separate out images as a separate service , These are simple data load balancing , Spread the pressure across different machines . Sometimes it comes from web The pressure on the front end , It can also be a headache . How to spread the access of the same domain name to two or more machines ? This is actually another kind of load balancing ,nginx You can do it on your own , Just make a simple configuration .

nginx Not only as powerful web The server , It can also be used as a reverse proxy server , and nginx You can also implement dynamic according to the scheduling rules 、 Separation of static pages , You can follow the poll 、ip Hash 、URL Hash 、 Weight and other ways to do load balancing for back-end servers , At the same time, it also supports the health check of back-end servers .
Nginx Some basic knowledge of load balancing :

nginx Of upstream At present, we support 4 Ways of distribution

  1. polling ( Default )
    Each request is allocated to different back-end servers in chronological order , If the backend server down fall , Can be eliminated automatically .
  2. weight
    Specify polling probability ,weight Proportional to the access rate , Used in case of uneven performance of back-end server .
  3. ip_hash
    Per request by access ip Of hash Result distribution , In this way, each visitor has fixed access to a back-end server , Can solve session The problem of .
  4. fair( The third party )
    Allocate requests based on the response time of the back-end server , Priority allocation with short response time .
     Insert picture description here
    Of course, load balancing is generally done in the service is relatively large 、 When there are many access requests . I also have only one server , For the time being, the demand is not so big , So it won't be available for the time being , Take a note, I believe it will be used in the future
server host IP1: port ;
server host IP2: port ;
server host IP1: port ;
server host IP2: port ;
listen 80;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
listen 80;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

nginx Document distribution


Generally, there are two main models for making websites :MVC、MVVC, Both are used very much at present ,VR360 yes MVVC Model , Our blog system is directly used tale Of , He uses MVC Model . I prefer to use MVVC Model , Of course, each has its own advantages , Explain first MVC and MVVC What's the difference between models :

MVC The model is Model、View、Control The initial of three words , Obviously, it divides the whole system into three modules , People who have done development know this, so I won't elaborate on it , We focus on V and MC In between ,MVC The model is to View Layer data rendering is directly placed on the server side , After rendering, the static file is sent to the client for display . and MVVC The model is different , It's also called Double MVC Model , Equivalent to the client 、 The server is a MVC Model ,View The layer is more about rendering on the client side . At the end of the day :MVC Relatively safer , But it will increase server pressure ;MVVC No, MVC Security , But leave the data rendering to each client , It takes a lot of pressure off the server .

 Insert picture description here

nginx Solving cross domain problems

Above introduction MVC and MVVC The difference is a little bit ,MVC The system server pressure under the model will be relatively large , This is because static files and service processing are placed on the same server , So if you don't want to open one alone Tomcat The server , It can be used at this time nginx To distribute static files , Put static files directly in nginx Under the server ,Tomcat Service is the only task to handle , It's going to reduce the pressure a little bit .

Usually when doing website development ( In particular, the front and back-end separation development ) There's a headache : The request was rejected across domains !.

First of all, what is cross domain ?

It means that the browser can't execute scripts of other websites . It's caused by the browser's homology strategy , Security restrictions imposed by the browser . domain name 、 Different ports belong to different domains ,XMLHttpRequest The request belongs to a cross domain ( That is to say AJAX).

So how to solve the cross domain problem ? There are generally three ways :

  1. When the server configures the filter, all domains are allowed to access , Not recommended , Because it's not safe .
  2. Front and back data use JSONP Format transfer , It's wrapping data in JS Script , Let the browser think this data is js file , The browser will release .
  3. Use nginx agent , Static files are placed in nginx in , The service side and nginx In the same server host , At this time, the requested domain and the server domain are under the same host and use nginx I've been a reverse agent , It's the same domain .

I've been mining for servers all the time , Maybe I'm still in a pit , There is still a lot to learn , If there is anything wrong with the above, please point it out to me , At the same time, welcome to learn and exchange with me .ヾ(◍°∇°◍)ノ゙

My personal blog address


  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple