Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of deploying reverse proxy load balancing with nginx in Golang Project

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

The knowledge of this article "Golang project with nginx deployment reverse proxy load balancing method" is not understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Golang project with nginx deployment reverse proxy load balancing method" article.

Independent deployment

The Go language supports cross-platform cross-compilation, which means that we can write code on Windows or Mac platforms and compile the code into programs that can run on Linux amd64 servers.

For simple projects, we usually just need to copy the compiled binaries to the server and set them to run as a background daemon.

Compile

Compilation can be done by either the following command or by writing makefile.

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build-o. / bin/bluebell

Let's assume that we upload locally compiled bluebell binaries, configuration files, and static files to the server's / data/app/bluebell directory.

In addition, if you dislike that the compiled binary is too large, you can add the-ldflags "- s-w" parameter to remove the symbol table and debugging information, which can generally be reduced by 20%.

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build-ldflags "- s-w"-o. / bin/bluebell

If it is still too large, you can continue to use the upx tool to compress the binary executable.

After we compile the bluebell project, the directory structure of the relevant necessary files is as follows:

├── bin │ └── bluebell ├── conf │ └── config.yaml ├── static │ ├── css │ │ └── app.0afe9dae.css │ ├── favicon.ico │ ├── img │ │ ├── avatar.7b0a9835.png iconfont.cdbe38a0.svg logo.da56125f.png search.8e85063d. Png │ └── js │ ├── app.9f3efa6d.js │ ├── app.9f3efa6d.js.map │ ├── chunk-vendors.57f9e9d6.js │ └── chunk-vendors.57f9e9d6.js.map └── templates └── index.htmlnohup

Nohup is used to run commands in the system background without hanging up, which means that the terminal that exits the command will not affect the running of the program.

We can use the nohup command to run the application as a background daemon. Since the nohup command tool is installed by default in mainstream Linux distributions, we can directly type the following command to start our project:

Sudo nohup. / bin/bluebell conf/config.yaml > nohup_bluebell.log 2 > & 1 &

Where:

. / bluebell conf/config.yaml is the startup command of our application

Nohup. & means to execute the startup command of the above application without hanging up in the background

> nohup_bluebell.log means to redirect the standard output of the command to the nohup_bluebell.log file

2 > & 1 means that the standard error output is also redirected to standard output. Combined with the previous item, all the output of executing commands is directed to the nohup_bluebell.log file.

The above command returns the process id after execution.

[1] 6338

Of course, we can also view the progress of bluebell-related activities with the following command:

Ps-ef | grep bluebell

Output:

Root 6338 4048 0 08:43 pts/0 00:00:00. / bin/bluebell conf/config.yamlroot 6376 4048 0 08:43 pts/0 00:00:00 grep-- color=auto bluebell

At this point, you can open a browser and enter the public network ip: port of the http:// server to view the display effect of the application.

Supervisor

Supervisor is a popular general process management program in the industry, which can turn an ordinary command line process into a background daemon, monitor the running status of the process, and restart it automatically when the process exits abnormally.

First use yum to install supervisor:

If you have not already installed EPEL, you can complete the installation by running the following command, or skip this step if you have:

Sudo yum install epel-release

Install supervisor

Sudo yum install supervisor

The configuration file for Supervisor is: / etc/supervisord.conf, and the configuration files for applications managed by Supervisor are placed in the / etc/supervisord.d/ directory, which can be configured in include in supervisord.conf.

[include] files = / etc/supervisord.d/*.conf

Start the supervisor service:

Sudo supervisord-c / etc/supervisord.conf

We create a configuration file called bluebell.conf in the / etc/supervisord.d directory, as shown below.

[program:bluebell]; program name user=root; user command=/data/app/bluebell/bin/bluebell / data/app/bluebell/conf/config.yaml who executes the program; startup file path project configuration file path directory=/data/app/bluebell/; directory where the command is executed; signal autostart=true sent on restart; whether to automatically start autorestart=true; whether to restart stdout_logfile=/var/log/bluebell-stdout.log automatically Standard output log location stderr_logfile=/var/log/bluebell-stderr.log; standard error log location

After creating the configuration file, restart the supervisor service

Sudo supervisorctl update # update the configuration file and restart the related program sudo supervisorctl status bluebell # View the running status of bluebell: sudo supervisorctl restart bluebell # restart sudo supervisorctl start bluebell # start

Output:

Bluebell RUNNING pid 10918, uptime 0:05:46

Finally, add some common supervisr management commands:

Supervisorctl status # View all task status supervisorctl shutdown # close all task supervisorctl start program name # start task supervisorctl stop program name # close task supervisorctl reload # restart supervisor

The next step is to open a browser to see if the site is working properly.

With nginx deployment

In complex scenarios such as static file separation, configuration of multiple domain names and certificates, and self-built load balancing layer, we generally need to deploy our programs with third-party web servers (Nginx, Apache).

Forward proxy and reverse proxy

Forward agent can be simply understood as the agent of the client. The one you use to visit the website outside the wall belongs to the forward agent.

Reverse proxy can be simply understood as the proxy of the server, which is usually referred to as Nginx and Apache.

Nginx is a free, open source, high-performance HTTP and reverse proxy service, mainly responsible for loading some heavily visited sites. Nginx can be used as a stand-alone Web service, or it can be used as a reverse proxy for Apache or other Web services. It can handle more concurrent connections than Apache,Nginx, and the memory footprint of each connection is very small.

Install nginx using yum

There is a Nginx installation package in the EPEL warehouse. If you have not already installed EPEL, you can complete the installation by running the following command:

Sudo yum install epel-release

Install nginx

Sudo yum install nginx

After the installation is complete, execute the following command to set Nginx boot:

Sudo systemctl enable nginx

Start Nginx

Sudo systemctl start nginx

View the running status of Nginx:

Sudo systemctl status nginxNginx profile

With the nginx installed using the above method, all related configuration files are in the / etc/nginx/ directory. The main configuration file for Nginx is / etc/nginx/nginx.conf.

By default, there is an example of a configuration file for nginx.conf.default, which can be used as a reference. You can create different profiles for multiple services (it is recommended to create a separate profile for each service (domain name)), and each separate Nginx service profile must end with .conf and be stored in the / etc/nginx/conf.d directory.

Nginx common commands

Add a few common Nginx commands.

Nginx-s stop # stop Nginx service nginx-s reload # reload configuration file nginx-s quit # smooth stop Nginx service nginx-t # Test profile is correct Nginx reverse proxy deployment, no load balancer

We recommend using nginx as a reverse proxy to deploy our program and modify the nginx configuration file as follows.

Worker_processes 1; # worker process events {worker_connections 1024; # connections} http {include mime.types; # default configuration default_type application/octet-stream; # default configuration sendfile on; keepalive_timeout 65; # timeout server {# server group listen 80; # nginx listener port server_name localhost # the domain name of the service access_log / var/log/bluebell-access.log; # access log error_log / var/log/bluebell-error.log; # error log location / {# access / root all paths, reverse proxy from 80 to 8084 proxy_pass http://127.0.0.1:8084; 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;}

Execute the following command to check the configuration file syntax:

Nginx-t

Execute the following command to reload the configuration file:

Nginx-s reload

The next step is to open a browser to see if the site is working properly.

Nginx reverse proxy deployment with load balancer

Of course, we can also use nginx's upstream configuration to add multiple server addresses to achieve load balancing.

Worker_processes 1; # worker process events {worker_connections 1024; # connections} http {include mime.types; # default configuration default_type application/octet-stream; # default configuration sendfile on; keepalive_timeout 65; # timeout # load balancer backend is the group name upstream backend {server 127.0.0.1 # you need to fill in the real available address here. By default, you need to poll # server backend1.example.com; # server backend2.example.com;} server {# server group listen 80; # nginx listens to the domain name access_log / var/log/bluebell-access.log of the port server_name localhost; # service. # access log error_log / var/log/bluebell-error.log; # error log location / {# access / root all paths, reverse proxy from 80 to 8084 proxy_pass http://backend/; # load balancer group name 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;} Nginx separate dynamic and static file request

The above configuration is simply to use nginx as a reverse proxy to handle all requests and forward them to our Go program for processing. In fact, we can also choose to use nginx to handle the static file request directly, and forward the dynamic processing request of the API interface class to the back-end Go program for processing.

Let's continue to modify our nginx configuration file to achieve the above functionality.

Specify the path of the static file to prevent the front-end splicing interface, the back-end does not have. 404 situation after refresh

Worker_processes 1 leading events {worker_connections 1024;} http {include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server {listen 80; server_name bluebell; access_log / var/log/bluebell-access.log; error_log / var/log/bluebell-error.log # static file request: location ~. *\. (gif | jpg | jpeg | png | js | css | eot | ttf | woff | svg | otf) ${access_log off; expires 1d; root / data/app/bluebell; # specifies the path of the static file to prevent the front end from stitching, but the backend does not have it. Index.html page request # since it is a single page application, use try_files to avoid the 404 problem when refreshing the page location / {root / data/app/bluebell/templates; # specify the path where the index.html front-end file is located: index index.html; try_files $uri $uri/ / index.html # all requests end up pointing to index.html} # API request location / api {proxy_pass http://127.0.0.1:8084; 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;} front and rear deployment separately

The front-end code does not need to be deployed to the same server, or it can be deployed separately to different servers. The following figure shows how the front-end service forwards the API request to the back-end service.

In the above deployment scenario, all browser requests directly access the front-end service, while in the deployment mode where the browser directly accesses the back-end API service, as shown below.

At this point, the front end and the back end are usually not under the same domain, and we also need to add cross-domain support to the back-end code.

The github.com/gin-contrib/cors library is used here to support cross-domain requests.

Allow all requests to cross domains

The simplest configuration that allows cross-domain is to use cors.Default (), which allows all cross-domain requests by default.

Func main () {router: = gin.Default () / / same as / / config: = cors.DefaultConfig () / / config.AllowAllOrigins = true / / router.Use (cors.New (config)) router.Use (cors.Default ()) router.Run ()}

In addition, you can use cors.Config to customize specific configuration items related to cross-domain requests:

Package mainimport ("time"github.com/gin-contrib/cors"github.com/gin-gonic/gin") func main () {router: = gin.Default () / / CORS for https://foo.com and https://github.com origins Allowing: / /-PUT and PATCH methods / /-Origin header / /-Credentials share / /-Preflight requests cached for 12 hours router.Use (cors.New (cors.Config {AllowOrigins: [] string {"https://foo.com"}, AllowMethods: [] string {" PUT "," PATCH "}) AllowHeaders: [] string {"Origin"}, ExposeHeaders: [] string {"Content-Length"}, AllowCredentials: true, AllowOriginFunc: func (origin string) bool {return origin = = "https://github.com"}, MaxAge: 12 * time.Hour })) router.Run ()} the above is the content of this article on "Golang project with nginx deployment reverse proxy load balancing method" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report