我有一个带有 Angular 和 NodeJS 的存储库。 我在jenkins中执行:
# install globally
npm install -g bower
npm install -g gulp
# install
bower install
npm install
# build dist folder
gulp build
现在我的根目录中有:
Dockerfile.nginx Dockerfile.nodejs README.md bower.json dist gulp.config.js gulpfile.js node_modules package.json server.js src
我正在将 dist 文件夹复制到 nginx 容器中。所以我主持了 Angular. (使用 dockerfile)
FROM nginx
# copy folder
COPY dist /usr/share/nginx/html/dist
我正在复制:gulp.config.js gulpfile.js node_modules server.js
到我的nodejs容器。 (也带有 dockerfile)
FROM node
# Create app directory
RUN mkdir -p /usr/src/www
WORKDIR /usr/src/www
# copy
COPY node_modules /usr/src/www/
COPY gulpfile.js /usr/src/www/
COPY gulp.config.js /usr/src/www/
COPY server.js /usr/src/www/
EXPOSE 8080
CMD [ "node", "server.js" ]
我运行 2 个容器,但 nginx 不与 Nodejs 通信
编辑1: 启动容器:
docker run -d -p 8888:8888 --name "nodejs" localhost:5000/test/nodejs:1
docker run -d -p 80:80 --name "nginx" localhost:5000/test/nginx:1
编辑2:我的nginx.conf看起来像这样:
http {
upstream node-app {
least_conn;
server nodejs:8888 weight=10 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location /dist {
alias /usr/share/nginx/html/dist/;
}
location ~* /api {
#location / {
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;
}
}
}
我的 server.js 看起来像:
app.get('/api/hello', requestProxy({
url: xxx + "/hello"
}));
最佳答案
您需要公开 nginx(Angular) 容器将连接的 Node.js 容器的端口。 请参阅Connect using network port mapping docker 文档部分。
更新:我认为,您需要将 nginx 配置文件配置到 Node 容器。 This question有与您的用例相关的示例 nginx 文件(尽管与容器无关)。
编辑:要将 Node 应用程序与 nginx 映射,您首先需要将 Node 容器与 nginx 容器链接。
docker run -d -p 80:80 --name "nginx" --link nodejs:nodejs localhost:5000/test/nginx:1
当您将 Node 容器与 nginx 容器链接时, Node 容器的地址将保存在/etc/hosts 中。因此 nginx 容器可以从那里访问 Node 的地址。
因此,在 nginx 配置文件中,nodejs 将作为 Nodejs 的容器地址进行访问:
http {
upstream node-app {
server nodejs:8888 weight=10 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location / {
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;
}
}
}
关于node.js - 如何将 NodeJS 与 Angular 连接(在 Nginx 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34872979/