Skip to content

Instantly share code, notes, and snippets.

@tommyjtl
Last active August 15, 2023 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommyjtl/d2bc4e86bd00f4f391aa99fb5291e411 to your computer and use it in GitHub Desktop.
Save tommyjtl/d2bc4e86bd00f4f391aa99fb5291e411 to your computer and use it in GitHub Desktop.
Serving Secured WebSocket Server (wss://) via Nginx and PM2.

This gist demonstrated the example use of serving secured WebSocket server (wss://) using Python's websockets via Nginx and PM2 the process manager. Have not tested thoroughly on production, so this is only for development use.

  • For fullchain.pem and privkey.pem, you will need use cerbot to generate them.
  • For pm2.json, run pm2 start pm2.json to run the WebSocket server in the background.
server {
listen 80;
server_name your.domain.name;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name your.domain.name;
ssl_certificate /etc/letsencrypt/live/path/to/your/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/path/to/your/privkey.pem; # managed by Certbot
ssl_session_timeout 5m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
# proxy_set_header X-Forwarded-For $remote_addr;
# proxy_set_header Host $http_host;
proxy_pass http://websocket_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
upstream websocket_upstream {
server 127.0.0.1:8765;
}
{
"name": "your-websocket-server",
"watch": true,
"script": "wss-server.py",
"interpreter": "/path/to/your/python/executable"
}
import asyncio
import websockets
from websockets.server import serve
import logging
logger = logging.basicConfig(
format="%(asctime)s %(message)s",
level=logging.INFO,
)
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main():
async with serve(echo,
'0.0.0.0',
8765,
logger=logger,
):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment