使用Docker容器化的NodeJS和Nginx

4
我有一个NodeJS应用程序,它已经被docker化,我还有一个NGINX docker容器,可以在docker容器中的NodeJS进程之间进行负载均衡。我能够成功地使用curl访问两个NodeJS服务器,但是NGINX找不到上游服务器。
以下是nginx配置:
upstream app {
    least_conn;              # Use Least Connections strategy
    server 127.0.0.1:3000;   # NodeJS Server 1
    server 127.0.0.1:3001;   # NodeJS Server 2
}
server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example.com-access.log;
    error_log  /var/log/nginx/example.com-error.log error;

    # Browser and robot always look for these
    # Turn off logging for them
    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { log_not_found off; access_log off; }

    # Handle static files so they are not proxied to NodeJS
    # You may want to also hand these requests to other upstream
    # servers, as you can define more than one!
    location ~* (images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
      root /usr/share/nginx/html;
    }

    # pass the request to the node.js server
    # with some correct headers for proxy-awareness
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://app/;
        proxy_redirect off;

        # Handle Web Socket connections
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Proxy requests to the mobile api to the mobile api servers (old version of Android App uses m.goodrx.com URLs)
    location /mobile-api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://www.goodrx.com/mobile-api;
        proxy_redirect off;

        # Handle Web Socket connections
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

我随后启动节点容器绑定端口3000和3001,nginx容器绑定端口80。当使用curl命令访问127.0.0.1:80时,出现了“Bad Request”的错误,但是访问127.0.0.1:3000和127.0.0.1:3001却可以正常工作。有什么想法关于NGINX代理出了什么问题吗?
1个回答

0

127.0.0.1或localhost指向nginx容器。 你可以在这里检查我的答案,但基本上你需要使用--add-host docker:<IP地址>运行nginx容器,然后更改nginx配置:

upstream app {
    least_conn;              # Use Least Connections strategy
    server docker:3000;   # NodeJS Server 1
    server docker:3001;   # NodeJS Server 2
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接