【问题标题】:Nginx connection refused, when trying to connect to node app as reverse proxy尝试作为反向代理连接到节点应用程序时,Nginx 连接被拒绝
【发布时间】:2017-07-28 23:44:12
【问题描述】:

我尝试使用 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

我的节点 Dockerfile:

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 Dockerfile

FROM nginx:1.10

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

在 npm start 这将运行:

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。

【问题讨论】:

    标签: node.js nginx docker reverse-proxy


    【解决方案1】:

    c-福尔摩斯,

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

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

    proxy_pass http://app:7770;

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

    【讨论】:

      【解决方案2】:

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

      proxy_pass http://app:7770;

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-05
        • 2021-12-23
        • 1970-01-01
        • 2017-02-16
        • 2016-08-12
        • 2021-11-16
        • 1970-01-01
        • 2019-10-20
        相关资源
        最近更新 更多