我想用反向代理设置一个websocket服务器。为此,我使用python中的简单websocket服务器和nginx反向代理创建了一个docker-compose。
设定:
docker-compose.yml:
version: '2.4'
services:
wsserver:
restart: always
ports:
- 8765:8765
build:
context: ./server
dockerfile: Dockerfile
ngproxy:
image: nginx
ports:
- 8020:80
- 5000:5000
restart: always
depends_on:
- wsserver
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.conf
nginx.conf:
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server wsserver:8765;
}
server {
listen 5000;
location / {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
}
Websocket服务器:
Dockerfile:
FROM python:3
RUN pip install websockets
RUN pip install asyncio
COPY server.py /
CMD [ "python", "./server.py" ]
server.py:
import asyncio
import websockets
import os
async def echo(websocket, path):
async for message in websocket:
print(message)
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, '0.0.0.0', 8765))
asyncio.get_event_loop().run_forever()
简单的ws客户端,可帮助运行测试(我也使用了Chrome扩展程序):
client.py:
import asyncio
import websockets
async def hello(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("Hello world!")
resp = await websocket.recv()
print(resp)
asyncio.get_event_loop().run_until_complete(
hello('ws://localhost:5000'))
# Without reverse proxy -> ws://localhost:8765
问题:
当我尝试连接(使用客户端或使用Chrome扩展程序)时,出现以下错误:
WebSocket connection to 'ws://localhost:5000/' failed: Connection closed before receiving a handshake response
我的步骤有什么问题吗?
更多信息:
- 当我尝试在没有反向代理的情况下连接到websocket时,它可以工作。
- 我的Nginx错误日志中没有消息。
- 所有配置均基于nginx docs:nginx websocket
- 我已经检查了以下线程:Docker NGINX代理未转发Websockets,使用浏览器WebSocket和docker-compose和Docker nginx websocket代理配置NGINX反向代理-客户端在等待请求时关闭了连接
谢谢!
经过一番研究之后,我终于找到了问题所在:我将本地nginx配置映射到了容器上的错误文件。
所以要修复它,请更改我的docker-compose.yml中的音量
从:
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.conf
至:
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
并且还从nginx.conf中删除了de http:
nginx.conf
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server wsserver:8765;
}
server {
listen 5000;
location / {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句