Nginx部署Gin Web服务

809 阅读2分钟

简介

Go是一门开放源代码的编程语言,它与其他语言相比有着更好的性能和更高的并发性。Gin是一个用于构建Web应用程序的轻量级框架,它提供了简单而强大的API来实现Web应用程序和微服务的开发。在本文中,我们将介绍如何使用Nginx部署Go Gin开发的Web服务,并提供centos7系统上的Nginx安装步骤。

准备工作

在开始之前,需要确保您已经在centos7系统上安装了以下软件:

  • Go 1.14或更高版本
  • Nginx
  • Git

步骤

安装Nginx

  1. 使用yum安装Nginx:

    yum install nginx
    
  2. 启动Nginx并使其在系统启动时自动启动:

    systemctl start nginx
    systemctl enable nginx
    
  3. 验证Nginx是否已成功安装:

    在浏览器中输入服务器的IP地址或域名,如果能看到“Welcome to nginx!”的响应页面,表示Nginx已经成功安装。

创建Gin Web服务

  1. 在终端或命令行中使用以下命令创建Gin Web服务:

    mkdir myweb
    cd myweb
    go mod init myweb
    go get -u github.com/gin-gonic/gin
    
  2. 然后,创建一个名为main.go的文件,并将以下内容添加到该文件中:

    package main
    
    import (
        "net/http"
    
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        r := gin.Default()
    
        r.GET("/", func(c *gin.Context) {
            c.String(http.StatusOK, "Hello, world!")
        })
    
        r.Run(":8080")
    }
    
  3. 测试Web服务:

    在终端或命令行中使用以下命令启动Web服务:

    go run main.go
    

    如果一切正常,您应该在浏览器中输入http://localhost:8080并看到“Hello, world!”的响应。

配置Nginx

  1. 打开Nginx配置文件/etc/nginx/nginx.conf

    vi /etc/nginx/nginx.conf
    
  2. 将以下内容添加到配置文件中:

    server {
        listen 80;
    
        server_name example.com;
    
        location / {
            proxy_pass http://localhost:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    

    其中,server_name是您的域名或服务器的IP地址。

  3. 使用以下命令检查Nginx配置是否正确:

    sudo nginx -t
    
  4. 如果配置正确,则重新加载Nginx:

    sudo systemctl reload nginx
    
  5. 测试部署:

    在浏览器中输入您的服务器的IP地址或域名。如果一切正常,您应该看到“Hello, world!”的响应。

    注意:如果您使用了防火墙(例如firewalld),请确保允许流量通过端口80。

    sudo firewall-cmd --add-service=http --permanent
    sudo firewall-cmd --add-service=https --permanent
    sudo firewall-cmd --reload
    

恭喜,您已经成功地使用Nginx部署了Go Gin开发的Web服务!

下一章节我们来学习一下docker打包部署gin web服务, 敬请期待!