我一直在为我的微服务nest js应用程序使用docker和nginx,为每个服务设置反向代理,以便我可以在同一端口的不同路径下访问它们。
Dockerfile(每个服务相同)
# Use a Node.js LTS version as the base image
FROM node:lts-alpine
# Create a working directory inside the container
WORKDIR /usr/src/app
# Copy the package.json and package-lock.json files to the working directory
COPY package*.json ./
# Install the dependencies
RUN npm install
# Copy the rest of the files to the working directory
COPY . .
# Expose the port 3000 so that the application can be accessed from outside the container
EXPOSE 3000
# Run the application
CMD ["npm", "run", "start:dev"]
字符串
nginx.conf
worker_processes 1;
events { worker_connections 1024; }
http {
upstream users {
server user-api:3000;
}
upstream academic {
server academic-api:3000;
}
server {
listen 80;
location /users/ {
proxy_pass http://users/;
}
location /academic/ {
proxy_pass http://academic/;
}
}
}
型
- docker-compose.yaml*
version: "3"
services:
academic-api:
container_name: academic-api
image: academic-api
build:
context: ./academic-api
dockerfile: Dockerfile.dev
volumes:
- ./academic-api:/usr/src/app
- /usr/src/app/node_modules
command: npm run start:dev
restart: unless-stopped
user-api:
container_name: user-api
image: user-api
build:
context: ./user-api
dockerfile: Dockerfile.dev
volumes:
- ./user-api:/usr/src/app
- /usr/src/app/node_modules
command: npm run start:dev
restart: unless-stopped
nginx:
container_name: nginx
image: nginx:latest
ports:
- "3000:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- user-api
- academic-api
restart: unless-stopped
型
我可以在http://localhost:3000/academic/和http://localhost:3000/users/下访问我的2个服务,一切正常。
现在我想将WebSocket添加到学术API中,我正在使用socket io。默认情况下,WebSocket服务器也会在端口3000上启动,这也是http服务器端口。
import { OnModuleInit } from "@nestjs/common";
import {
ConnectedSocket,
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from "@nestjs/websockets";
import { Server } from "socket.io";
@WebSocketGateway()
export class GatewayService implements OnModuleInit {
@WebSocketServer()
server: Server;
onModuleInit() {
console.log("GatewayService initialized");
this.server.on("connection", (socket) => {
console.log("Socket connected => " + socket.id);
});
}
}
型
但是我不能在nginx代理下的docker环境中工作。基本上,我希望能够连接到WebSocket,如果我击中http://localhost:3000/academic/使用websocket协议使用 Postman 。
但是,如果我在端口3000上本地运行学术API服务器,我就可以让它工作。当我使用http协议时,它连接到http服务器,如果我使用WebSocket协议,它连接到websocket服务器。
2条答案
按热度按时间mw3dktmi1#
参考nginx文档,请尝试使用以下
nginx.conf
:字符串
https://www.nginx.com/blog/websocket-nginx/
b5buobof2#
我最终通过在不同的路径上启动WebSocket服务器并更新Nginx conf和客户端握手路径来使它工作。
个字符
最后通过
http://localhost:3000/academic/ws/?EIO=4&transport=websocket
连接到客户端