在 Web 应用程序中使用 nginx 服务器转到 Web 服务器

Go web server with nginx server in web application

抱歉,我无法通过 Google 搜索找到此答案 似乎没有人清楚地解释纯 Go 网络服务器之间的区别 和 nginx 反向代理。前面好像大家都用nginx 用于网络应用程序。

我的问题是,虽然 Go 具有所有 http 服务功能, 使用 nginx 比使用纯 Go Web 服务器有什么好处?

在大多数情况下,我们在这里为所有路由设置 Go 网络服务器 并在前面有nginx配置。

类似于:

limit_req_zone $binary_remote_addr zone=limit:10m rate=2r/s;

server {
    listen 80;

    log_format lf '[$time_local] $remote_addr ;

    access_log /var/log/nginx/access.log lf;
    error_log /var/log/nginx/error.log;

    set_real_ip_from 0.0.0.0/0;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
    server_name 1.2.3.4 mywebsite.com;
}

当我们有这个 Go 时:

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

nginx 和 Go web 服务器的流量是否不同? 如果不是,为什么我们有两层网络服务器?

请帮助我理解这一点。

谢谢,

在这种情况下使用 nginx 的一般想法是通过 nginx 提供静态资源并允许 Go 处理其他所有事情。

在 nginx 中搜索 "try_files"。它允许检查磁盘是否存在文件并直接提供它,而不必在 Go 应用程序中处理静态资产。

没有什么能阻止您直接处理来自 Go 的请求。

另一方面,nginx 提供的一些开箱即用的功能可能很有用,例如:

  • 处理许多虚拟服务器(例如在 app.example.com 上响应并在 www.example.com 上响应不同的应用程序)

  • 某些路径中的 http 基本身份验证,比如 www.example。com/secure

  • 访问日志

  • 等等

所有这些都可以在 go 中完成,但需要编程,而在 nginx 中,只需编辑 .conf 文件并重新加载配置即可。 Nginx 甚至不需要重新启动即可进行此更改。

(从 "process" 的角度来看,nginx 可以由具有 root 权限的运维人员管理,运行 在一个众所周知的端口中,而开发人员将他们的应用程序部署在更高的端口上。 )

这个问题之前已经被问过几次了[1]但是为了后代:

It depends.

Out of the box, putting nginx in front as a reverse proxy is going to give you:

  • Access logs
  • Error logs
  • Easy SSL termination
  • SPDY support
  • gzip support
  • Easy ways to set HTTP headers for certain routes in a couple of lines
  • Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)

The Go HTTP server is very good, but you will need to reinvent the wheel to do some of these things (which is fine: it's not meant to be everything to everyone).

I've always found it easier to put nginx in front—which is what it is good at—and let it do the "web server" stuff. My Go application does the application stuff, and only the bare minimum of headers/etc. that it needs to. Don't look at putting nginx in front as a "bad" thing.

此外,为了扩展我在那里的回答,还有崩溃恢复的问题:您的 Go 应用程序不受配置语言的限制,可以做 很多 的事情.

其中一些可能会使您的程序崩溃。将 nginx(或 HAProxy,或 Varnish 等)作为反向代理可以为您提供一些请求缓冲(以允许您的程序重新启动)and/or 从其本地缓存(即您的静态主页)提供陈旧内容,这可能比让浏览器超时并提供 "cannot connect to server error".

要好

另一方面,如果您要构建小型内部服务,'naked'带有您自己的日志记录库的 Go Web 服务器会更易于管理(在操作方面)。

如果您想要将所有内容保留在您的 Go 程序中,请查看 gorilla/handlers for gzip, logging and proxy header middleware, and lumberjack 日志轮换(否则您可以使用系统的日志记录工具)。