nginx和nodejs:连接上游时connect()失败(111:拒绝连接)

3
在我开始之前,我已经查看了所有我能找到的相似问题,并没有找到解决我的问题的答案。
我正在运行两个Docker容器,一个是用于nginx,另一个是用于node.js API。我使用nginx作为反向代理。
当我请求localhost/api/x时,我会收到502 bad gateway错误,并且nginx日志中也会有记录。
nginx_1 | 2015/08/15 15:30:30 [error] 9#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: X.X.X.X, server: _, request: "GET /api/x HTTP/1.1", upstream: "http://127.0.0.1:8543/x", host: "localhost"

我能够通过docker ps获取8543端口映射到我的电脑上,并且可以正常访问应用程序。这表明节点应用正在运行,并在监听正确的端口(8543)。我还可以从错误消息和重写日志中确定请求URI被正确重写了。
我已经为此苦苦思索了一段时间,但无法找出问题所在,如果您能提供任何帮助,将不胜感激!
我的nginx.conf:
user nginx nginx;

worker_processes auto;
worker_rlimit_nofile 8192;

events {
  worker_connections 8000;
}

error_log  /dev/stderr notice;
pid        /var/run/nginx.pid;

http {

  # Hide nginx version
  server_tokens off;

  rewrite_log on;

  # mime types
  include mime.types;
  default_type application/octet-stream;

  # Update charset_types due to updated mime.types
  charset_types text/xml text/plain text/vnd.wap.wml application/x-javascript application/rss+xml text/css application/javascript application/json;

  # Format to use in log files
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /dev/stdout main;

  keepalive_timeout 20;
  sendfile          on;
  tcp_nopush        on;

  # Nodejs API
  upstream api {
    server 127.0.0.1:8543;
  }

  # Reverse-proxy for the Riot API, S3, and our API
  server {
    listen [::]:80;
    listen 80;

    server_name _;

    charset utf-8;

    # Resolver
    resolver         8.8.8.8 valid=300s;
    resolver_timeout 10s;

    # API, reverse proxy our API
    location /api/ {
      limit_except GET {
        deny all;
      }
      rewrite ^/api(/.*)$ $1 break;
      proxy_pass http://api;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }
  }
}

我的nginx Dockerfile

# Set the base image to centos
FROM centos:7

# File Author
MAINTAINER Andrew Shapro

# Install nginx
RUN yum update -y && \
  yum -y install \
  curl \
  tar \
  openssl-devel \
  gcc \
  gcc-c++ \
  make \
  zlib-devel \
  pcre-devel \
  gd-devel \
  krb5-devel

# download and compile nginx
RUN curl -sLo nginx-1.9.2.tar.gz http://nginx.org/download/nginx-1.9.2.tar.gz \
  && mkdir /root/nginx_source \
  && tar -xzvf nginx-1.9.2.tar.gz -C /root/nginx_source --strip-components=1
COPY nginx_modules /root/nginx_modules
RUN cd /root/nginx_source \
  && ./configure \
    --user=nginx \
    --with-debug \
    --group=nginx \
    # --prefix=/user/share/nginx \
    # --sbin-path=/user/sbin/nginx \
    --conf-path=/etc/nginx/nginx.conf \
    --pid-path=/run/nginx.pid \
    --http-client-body-temp-path=/var/lib/nginx/body \
    --http-proxy-temp-path=/var/lib/nginx/proxy \
    --lock-path=/run/lock/subsys/nginx \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_auth_request_module \
    --with-http_addition_module \
    --with-http_gzip_static_module \
    --with-http_image_filter_module \
    --with-http_spdy_module \
    --with-http_sub_module \
    --with-ipv6 \
    --add-module=/root/nginx_modules/ngx_devel_kit \
    --add-module=/root/nginx_modules/ngx_aws_auth \
  && make \
  && make install \
  && rm -rf /root/nginx_modules /root/nginx_source \
  && mkdir --parents /var/lib/nginx

# Add nginx configs
RUN curl -sLo /usr/local/bin/ep https://github.com/kreuzwerker/envplate/releases/download/v0.0.8/ep-linux && chmod +x /usr/local/bin/ep
ADD nginx.conf /etc/nginx/nginx.conf
ADD mime.types /etc/nginx/mime.types

# Cleanup after build
RUN yum clean all \
  && yum autoremove -y

# Add nginx user
RUN adduser -c "Nginx user" nginx

EXPOSE 80

# Run nginx
# CMD ["stat", "/usr/local/nginx/sbin/nginx"]
CMD [ "/usr/local/bin/ep", "-v", "/etc/nginx/nginx.conf", "--", "/usr/local/nginx/sbin/nginx", "-c", "/etc/nginx/nginx.conf", "-g", "daemon off;" ]

我的 Node 应用

var express = require('express');

var app = express();

function allTheRoutes (req, res) {
  res.send('Hello World!');
}

app.get('/', allTheRoutes);
app.get('/*', allTheRoutes);
var app = require('./src/app');
var server = app.listen(process.env.PORT || 8543, process.env.HOST || '127.0.0.1', function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Listening at http://%s:%s', host, port);
});

我的Node Dockerfile

# Set the base image to centos
FROM centos:7

# File Author
MAINTAINER Andrew Shapro

# Install nginx
RUN yum update -y && \
  yum -y install curl

# Add nvm to $PATH
ENV PATH $PATH:$HOME/.nvm/bin

# Install nvm
RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.26.0/install.sh | bash

# Clean up
RUN yum clean all \
  && yum autoremove -y

# Add iojs to $PATH
ENV PATH $PATH:/root/.nvm/versions/io.js/v3.0.0/bin

# Intall iojs
RUN bash -lic 'nvm install iojs-v3.0'

# Install PM2
RUN npm install -g pm2

# NPM install
WORKDIR /app
ADD package.json /app/
RUN npm install

# Add app
ADD . /app

# Add run.sh
ADD run.sh run.sh
RUN chmod 755 run.sh

# Expose port
EXPOSE 8543

# run node
CMD ["./run.sh"]

./run.sh 运行命令 pm2 start -x app.js --no-daemon

docker-compose.yml

nginx:
    build: nginx
    ports:
      - "80:80"
    link: node
  node:
    build: node
    ports:
      - "8543"
    environment:
      - HOST=127.0.0.1
      - PORT=8543

你的Docker命令是什么,用于启动容器? - Michael
我正在使用docker-compose,在我的帖子底部添加了它。 - abramz
1个回答

10
根据你的 docker-compose.yml 文件,你将 nginx 容器的80端口映射到容器外的80端口,但是你将8543端口映射到了随机端口。当你告诉nginx去找127.0.0.1:8543时,它在主机中找不到此端口。
你已经将两个容器链接在一起,所以无需将8543端口暴露给主机来从nginx访问它。你需要做的是告诉它访问正确的主机:
# Nodejs API
upstream api {
    server node:8543;
}

这是因为当你连接容器时,Docker会在/etc/hosts中设置主机。你可以检查一下:

docker exec -ti nginx bash
cat /etc/hosts

当然,如果你暴露8543端口,它应该会起作用:

nginx:
build: nginx
ports:
  - "80:80"
link: node
node:
build: node
ports:
  - "8543:8543"
environment:
  - HOST=127.0.0.1
  - PORT=8543

了解更多有关Docker网络的信息:https://docs.docker.com/articles/networking/


谢谢,我会尝试一下。 - abramz
1
我认为 link 语法是错误的或已经改变了。应该使用 links:,然后像端口一样使用 - - jackncoke
请问@Leandro,您能否查看这个链接:https://stackoverflow.com/questions/51341709/load-balacing-nodejs-application-using-nginx-and-docker - codefreaK

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