JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

Go - Gin框架 - Nginx部署Go应用 go+nginx

wys521 2024-10-19 09:23:56 精选教程 33 ℃ 0 评论

一、简单讲解

1.1、常用命令

  • nginx:启动 Nginx
  • nginx -s stop:立刻停止 Nginx 服务
  • nginx -s reload:重新加载配置文件
  • nginx -s quit:平滑停止 Nginx 服务
  • nginx -t:测试配置文件是否正确
  • nginx -v:显示 Nginx 版本信息
  • nginx -V:显示 Nginx 版本信息、编译器和配置参数的信息
  • 1.2、涉及配置

    1、 proxy_pass:配置反向代理的路径。需要注意的是如果 proxy_pass 的 url 最后为/,则表示绝对路径。否则(不含变量下)表示相对路径,所有的路径都会被代理过去

    2、 upstream:配置负载均衡,upstream 默认是以轮询的方式进行负载,另外还支持四种模式,分别是:

    (1)weight:权重,指定轮询的概率,weight 与访问概率成正比

    (2)ip_hash:按照访问 IP 的 hash 结果值分配

    (3)fair:按后端服务器响应时间进行分配,响应时间越短优先级别越高

    (4)url_hash:按照访问 URL 的 hash 结果值分配


    二、部署

    在这里需要对 nginx.conf 进行配置,如果你不知道对应的配置文件是哪个,可执行 nginx -t 看一下

    $ nginx -t
    nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful

    2.1 配置 nginx.conf

    增加 server 片段的内容,设置 server_name 为 api.blog.com 并且监听 8081 端口,将所有路径转发到 http://127.0.0.1:8000/ 下

    worker_processes  1;
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        include       mime.types;
        default_type  application/octet-stream;
    
        sendfile        on;
        keepalive_timeout  65;
    
        server {
            listen       8081;
            server_name  api.blog.com;
    
            location / {
                proxy_pass http://127.0.0.1:8000/;
            }
        }
    }

    2.2、验证

    启动 go-gin-example

    回到 go-gin-example 的项目下,执行 make,再运行 ./go-gin-exmaple

    $ make
    github.com/EDDYCJY/go-gin-example
    $ ls
    LICENSE        README.md      conf           go-gin-example middleware     pkg            runtime        vendor
    Makefile       README_ZH.md   docs           main.go        models         routers        service
    $ ./go-gin-example 
    ...
    [GIN-debug] DELETE /api/v1/articles/:id      --> github.com/EDDYCJY/go-gin-example/routers/api/v1.DeleteArticle (4 handlers)
    [GIN-debug] POST   /api/v1/articles/poster/generate --> github.com/EDDYCJY/go-gin-example/routers/api/v1.GenerateArticlePoster (4 handlers)
    Actual pid is 14672
    重启 nginx
    $ nginx -t
    nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
    $ nginx -s reload
    访问接口
    http://api.blog.com:8081/auth?username=test&password=test123


    Tags:

    本文暂时没有评论,来添加一个吧(●'◡'●)

    欢迎 发表评论:

    最近发表
    标签列表