nginx 通过套接字配置向 json api 服务发送请求

nginx serve request to a json api service via sockets configuration

我的 grape 应用程序在本地主机上运行如下: bundle exec rackup -p 9292

然后去 http://localhost:9292/api/v1/ping,

您收到 json 回复 {"res":"pong"}

现在,我正在尝试将其投入生产。所以我决定在 puma 和 nginx 配置上运行它。 安装 puma 并在插座上运行它。

⇒  bundle exec puma -b unix:///tmp/my_app.sock
Puma starting in single mode...
* Version 2.10.2 (ruby 2.1.2-p95), codename: Robots on Comets
* Min threads: 0, max threads: 16
* Environment: development
env :: development
Service started, go to town.
* Listening on unix:///tmp/my_app.sock
Use Ctrl-C to stop

使用如下配置设置 nginx:

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;


    #access_log  logs/access.log  main;

    sendfile        on;

    upstream my_app {
        server unix:///tmp/my_app.sock;

   }
    server {
        listen       8989;
        server_name  my_app;


    root /Volumes/dev/my_app;

    access_log  /Volumes/dev/my_app/service/log/host.access.log;
    error_log  /Volumes/dev/my_app/service/log/error.access.log;

    location / {
       root              /Volumes/dev/my_app/;
       gzip_static       on;
       expires           max;
       add_header        Cache-Control public;
   }

}

而且我希望它的行为相同。我浏览到 http://localhost:8989/api/v1/ping 但是从 nginx 得到了 404 Not Found

错误日志显示:

2015/01/07 21:51:15 [error] 62300#0: *2 open() "/Volumes/dev/my_app/api/v1/ping" failed (2: No such file or directory), client: 127.0.0.1, server: my_app, request: "GET /api/v1/ping HTTP/1.1", host: "localhost:8989"

也许它认为它是服务静态内容?

在您的代码中,nginx 首先提供 root 的静态内容,而不是 upstream my_app。使用 root 仅提供静态文件,使用 upstream 将请求路由到应用服务器。这个简化的 nginx 配置可能对您有帮助:

upstream my_app {
  server unix:/tmp/my_app.sock;
}

server {
  listen 80;
  ...

  location / {
    proxy_pass http://my_app;
  }
}