Following are configuration files and instructions for using systemd
to create Unix domain sockets to handle incoming websocket requests. Websocket requests are proxied by nginx
.
While these instructions are for Debian 10, they should largely work on other Linux distributions. It may be necessary to change paths and the nginx
username, which is www-data
when installed with the Debian package manager.
user@host:~$ sudo apt update
user@host:~$ sudo apt install nginx python3 wget
user@host:~$ sudo mkdir -p /srv/websocket
user@host:~$ sudo chown user:user /srv/websocket/
user@host:~$ wget -O /srv/websocket/server.py https://gist.githubusercontent.com/sambeirne/7a1ee751b3b3da80106c67f7c69582a8/raw/06f0e881e4da79043d67ca41c294038164eef6b5/server.py
user@host:~$ python3 -m venv /srv/websocket/venv
user@host:~$ source /srv/websocket/venv/bin/activate
user@host:~$ pip install websockets
user@host:~$ sudo wget -O /etc/systemd/system/websocket@.socket https://gist.githubusercontent.com/sambeirne/7a1ee751b3b3da80106c67f7c69582a8/raw/06f0e881e4da79043d67ca41c294038164eef6b5/websocket@.socket
user@host:~$ sudo wget -O /etc/systemd/system/websocket@.service https://gist.githubusercontent.com/sambeirne/7a1ee751b3b3da80106c67f7c69582a8/raw/06f0e881e4da79043d67ca41c294038164eef6b5/websocket@.service
user@host:~$ sudo systemctl daemon-reload
user@host:~$ sudo systemctl enable --now websocket@{1..2}.socket
user@host:~$ systemctl status websocket@1.socket
● websocket@1.socket - websocket socket 1
Loaded: loaded (/etc/systemd/system/websocket@.socket; enabled; vendor preset: enabled)
Active: active (listening) since Wed 2020-12-23 19:50:11 UTC; 12s ago
Listen: /run/websocket/websocket1.sock (Stream)
Tasks: 0 (limit: 4915)
CGroup: /system.slice/system-websocket.slice/websocket@1.socket
user@host:~$ systemctl status websocket@1.service
● websocket@1.service - websocket daemon 1
Loaded: loaded (/etc/systemd/system/websocket@.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Two sockets are listening for connections. systemd
will start the associated services when a client connects.
user@host:~$ sudo wget -O /etc/nginx/sites-available/example.com https://gist.githubusercontent.com/sambeirne/7a1ee751b3b3da80106c67f7c69582a8/raw/06f0e881e4da79043d67ca41c294038164eef6b5/example.com
user@host:~$ sudo rm /etc/nginx/sites-enabled/*
user@host:~$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
user@host:~$ sudo nginx -s reload
user@host:~$ python -m websockets ws://localhost/socket/
Connected to ws://localhost/socket/.
> hello
< hello
Connection closed: code = 1000 (OK), no reason.
Messages entered at the interactive prompt should be echoed. Use Ctrl+C
to quit.