Node.JS 使用 Nginx 和 Docker 代理

Node.JS proxy with Nginx and Docker

我有一个带有 nodejs 的 docker 容器,我有一个带有 nginx 的 docker 容器。

我已经告诉我的 angular 使用 ec2-xxx:8888/api 来使用 api。 因为我 运行 我的 nodejs 容器有:

docker run -d -p 8888:8888 --name nodejs localhost:5000/test/node-js-image:1

所以我在我的亚马逊上映射了我 docker 的 8888。所以这是有效的。 我的 app.config.js 包含:

URL: 'http://ec2...',
      PORT: '8888',

我可以在 ec2:8888/api 上看到我的 api 但是让你的 api 可以被服务器访问并不能保存。所以我想 运行 我的 nodejs 是这样的:

docker run -d --name nodejs localhost:5000/test/node-js-image:1

所以没有把集装箱港口映射到我亚马逊的港口。但是我仍然需要从我的 nginx 容器访问 nodejs 容器。

我该怎么做? 我试过 nginx.conf:

http {    
        upstream node-app {
              least_conn;
              server nodejs:8888 weight=10 max_fails=3 fail_timeout=30s;

        }

        server {
              listen 80;

              location / {
                alias /usr/share/nginx/html/dist/;
                index index.html;
              }

              location /api {
                proxy_pass http://node-app;
                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;
              }
        }
}

但这不起作用。我只看到 HTML(没有 CSS)并且无法连接到 nodeJS 容器。

假设两个容器 运行 在同一台机器上,Docker 的 legacy container links are one possibility. Networking 是新的方法。

启动你的nodejs容器
docker run -d --name nodejs --expose 8888 <YOUR_NODEJS_IMAGE>

-p ... 相反,选项 --expose ... 使您的容器仅对 linked 容器可见。

用 link 到 nodejs:

启动你的 nginx 容器
docker run -d --name nginx --link nodejs <YOUR_NGINX_IMAGE>

为了从您的 nginx docker 容器访问 nodejs docker 容器,您必须使用由 docker 注入的环境变量。 This gist 举例说明如何做到这一点。