How to call microservices in the cloud platform

Under the front-end separation architecture, the front-end calls the back-end in the following two ways:

Ip+ port

The back-end service needs to be exposed through the ip+port method, because the requests are all sent from the browser, and any request sent from the browser needs to be accessible.
Disadvantages of using ip+port mode:

  1. The IP of the back-end service needs to be added to the dns to prevent the service from being unavailable after changing the IP
  2. If you do not assign a domain name, you need to expose the ip, which is a higher security risk
  3. Malicious access may cause the service to crash. Of course, if it is an intranet service, it is usually separated by several layers of firewalls. This is a bit unreasonable, and network security is not considered. This is not very good.

Reverse proxy

  1. Features of microservices in cloud platforms:
    1. As a microservice of the cloud platform, the backend does not need to expose microservices to users, but only needs to be exposed inside the cluster. Therefore, the backend microservices only need to be reachable within the cluster.
    2. The IP of the microservice may change at any time, and the operation and maintenance personnel do not know. Take k8s as an example. Microservices are deployed in pods. If one pod hangs, the other will be restarted immediately. At this time, the ip may change. If the front-end uses ip+port when calling the back-end, it will be 404.

Based on the above considerations, reverse proxy is a better way. The following describes how to implement it in detail. In fact, it is mainly to figure out the port. Please pay attention to the correspondence when you see the port.

  • The front-end request only writes the relative path, because in the end it will be forwarded to the back-end server by nginx. In order to separate the page display and the calling back-end, the unified calling of the back-end starts with apis, so that nginx will forward the request starting with /apis to the back end.
export function asyncGetAllDeps() {
    
    
	return function(dispatch){
    
    //dispatch
    // API
	    return fetch('/apis/getAllDeps',{
    
    
	        method: 'get',
	        headers: {
    
    
	          'Access-Control-Allow-Origin': 'assessment.frontend'
	        }
	    }).then(function(res){
    
    
	      return res.json();
	    }).then(function(data){
    
    
	      if(data !== undefined || data !== []){
    
    
	      	data.forEach((item)=> {
    
    
	      		item.key = item.DEPID;
	      	});
	      	dispatch(setallDepList(data));
	      }
	    }).catch((error) => {
    
    
	      console.log(error);
	    });
  	};
}
  • The above front-end code should be deployed to nginx, and the nginx image needs to be pulled. The dockerfile is as follows
    . Note that the port that the container should open is 80.
FROM nginx:1.17.10
COPY build/ /usr/share/nginx/html/
EXPOSE 80
  • Deploy the front-end yaml file, where the port of the container needs to be specified as 80, which should be consistent with the port number written in the dockerfile above.
spec:
      containers:
      - image: 前端打包成的镜像的地址
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          tcpSocket:
            port: 80
          timeoutSeconds: 1
        name: frontend
        ports:
        - containerPort: 80
          protocol: TCP
  • Configure the reverse proxy of nginx The
    configuration code to implement the reverse proxy is as follows:
location ^~/apis { # 自定义nginx接口前缀
	rewrite ^/apis/(.*)$ /$1 break; # 监听所有/apis前缀,是则转发后台api接口地址
	include uwsgi_params;
	proxy_pass http://backend:8080; # 后台api接口地址 这个修改
}

The location instruction matches the request beginning with /apis. If the match is successful, the rewrite instruction is used to rewrite the path and remove the prefix /apis, so that the backend does not need to modify the interface address. The front end adds the prefix /apis when requesting. After nginx matches the request that needs to be forwarded to the back end, the prefix /apis is removed. perfect.
Use proxy_pass to implement reverse proxy and forward the request to http://backend:8080. Here! ! ! Attention! ! ! backend is the service name of the backend (k8s is accessed by service name: port, others are not clear), 8080 is the port exposed by the backend service .
Here! ! ! Because during deployment, the port exposed to the outside world when pulling the image is all 80, so the port monitored by the http server should be 80 ! !

server {
	listen 80;
}

The full version of nginx is configured as follows, please call me Lei Feng.

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
	worker_connections 1024;
}
http {
	server_tokens off;
	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 65;
	types_hash_max_size 2048;
	include /etc/nginx/mime.types;
	default_type application/octet-stream;
	server {
		listen 80;# default_server;
		server_name assessment.frontend.com;
		root /usr/share/nginx/html;
		
		location ^~/apis { # 自定义nginx接口前缀
			rewrite ^/apis/(.*)$ /$1 break; # 监听所有/apis前缀,是则转发后台api接口地址
			include uwsgi_params;
			proxy_pass http://backend:8080; # 后台api接口地址 这个修改
		}
		error_page 404 /404.html;
			location = /40x.html {
		}
		error_page 500 502 503 504 /50x.html;
			location = /50x.html {
		}
	}
}
  • Deploying back-end microservices
    Here we need to expose port 8080 to the outside, because we configured in nginx to access 8080! !
spec:
      containers:
      - image: 后端微服务的镜像地址
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          tcpSocket:
            port: 8080
          timeoutSeconds: 1
        name: backend
        ports:
        - containerPort: 8080
          protocol: TCP

At this point, the front-end and back-end calls of the microservices in the cloud platform have been completed. Is it very good? Please be my fans.

Guess you like

Origin blog.csdn.net/u010659877/article/details/106331230