Nginx 连接被拒绝,当尝试连接到节点应用程序作为反向代理时

Nginx connection refused, when trying to connect to node app as reverse proxy

我试图用 docker 容器构建一个 Web 应用程序,但在尝试 运行 Nginx 作为我的节点应用程序的反向代理时,连接被拒绝。我不确定这是 nginx 服务器配置问题还是 docker-compose 配置问题。

[error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: foo.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:7770/", host: "foo.com"

我在点击 foo.com 时收到此错误,奇怪的是我的应用程序在引用端口号时工作,所以 foo.com:7770 运行 应用程序。

我的 nginx 服务器配置:

server {
    listen       80;
    server_name  foo.com;

    port_in_redirect off;
    autoindex on;

    location / {
        proxy_pass http://127.0.0.1:7770;
        proxy_redirect off;
        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;
    }
}

我的Docker Compose文件:(这里可能有些多余的东西)

version: "2"
services:
  nginx:
    build: ./nginx
    ports:
      - "80:80"
    depends_on:
      - app
    links:
      - app
  app:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "7770:7770"
    links:
      - mongo
    depends_on:
      - mongo
  mongo:
    image: mongo
    ports:
      - "27017:27017"
    volumes_from:
      - mongodata
    depends_on:
      - mongodata
  mongodata:
    image: tianon/true
    volumes:
      - /data/db

我的节点Docker文件:

FROM node:latest

ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/

WORKDIR /opt/app
ADD . /opt/app

EXPOSE 7770

CMD ["npm", "start"]

我的 ngnix Docker文件

FROM nginx:1.10

COPY default.conf /etc/nginx/conf.d/default.conf

在 npm 启动时这将 运行:

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(7770, function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:7770');
});

这是我在 docker 的第一个 运行,所以我可能混淆了一些事情。此外,我将 foo.com 指向 /private/etc/hosts 中的 127.0.0.1。

如果您想将流量从 nginx 路由到 app,您必须使用 proxy_passapp 容器的 IP 地址或 dns。使用 Docker Compose 服务可以通过服务名称相互发现,所以在 nginx conf 中更改

proxy_pass http://app:7770;

您不需要向外界发布端口 7770。同样对于 mongo 你不需要发布 27017 端口。

c-福尔摩斯,

首先,你需要记住每个容器都有自己的网络堆栈,所以你不能使用容器内部的localhost来访问docker主机中的服务运行 .

对于这个特定项目,您需要将 Nginx 服务器配置中的 proxy_pass 指令指向到达 app 容器的值。类似于:

proxy_pass http://app:7770;

您需要做对,因为在 docker-compose 上下文中,您的容器名称将映射到内部 DNS 条目。这样,您就不需要将应用程序容器的 7770 端口发布到外界,如果您的 MongoBD 将仅由您的应用程序容器访问,则您也不需要发布 27017 端口。