Connection refused on socket.connect (Django app deployed on uWSGI + Nginx) - python

I have a Django application deployed on a VM using uWSGI & Nginx setup.
I would like to print some data, by passing the required information to a printer that is configured on the same network using a socket:
printer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
printer_socket.connect(('10.125.125.2', 9001))
printer_socket.send(bytes(source='data', encoding='utf-8'))
Note: the IP address and the port are here for illustration purposes.
Problem: I get a Err 111 Connection refused error, however. The error is triggered at the printer_socket.connect step.
Additional information: The python code that initializes the socket, connects to the required IP address/Port and sends the data works fine when it's run from the python interactive shell.
Question: What do I need to configure in order to allow opening sockets from a django web application, deployed using uWSGI and Nginx?
Please keep in mind that the configuration of the project is out of the scope of this question. I don't have troubles configuring the app. The app works fine. I am specifically interested in how to allow opening sockets from a web app, served using uWSGI + Nginx setup
UPDATE
Here's the .ini configuration file for the uWSGI.
[uwsgi]
project = App
uid = user
base = /home/%(uid)
chdir = %(base)/%(project)
home = %(base)/Venv/%(project)
module = %(project).wsgi:application
# daemonize = %{base}/uwsgi/%{project}.log
logto = /home/user/logs/uwsgi/%{project}.log
master = true
processes = 5
socket = /run/uwsgi/%(project).sock
chown-socket = %(uid):www-data
chmod-socket = 777
vacuum = true
buffer-size=32768
Thank you.

Related

Create a default vhost to serve http request in uwsgi

I've uwsgi 2.0.19 on Linux running with the python plugin. I serve http(s) traffic with different applications each for a specific record of my managed domain using such kind of configuration to register them to the front uwsgi servers.
subscribe2 = server=x.x.x.x:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=x.x.x.x:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
subscribe2 = server=y.y.y.y:4443,key=domain.com:443,sni_key=/etc/ssl/private/domain.com.key,sni_cert=/etc/ssl/certs/domain.com.crt
Now when I reach one of the front servers to access a not-existing host, I received such error (the TCP connexion is closed I assume)
curl: (52) Empty reply from server
I would like to be able to have a default/catchall key for such case, that permits to return an HTTP status 404 as I would do in Apache using the _default_ vhost. is it possible.
In order to implement this, you need to define a fallback application using the http-subscription-fallback-key on the front uwsgi server
http-subscription-fallback-key=default
default is a standard application registered on the frontal uwsgi like any other application
subscribe2 = server=x.x.x.x:4443,key=default
subscribe2 = server=x.x.x.x:4443,key=default:80

How to serve CherryPy application in mulitple ports independently?

I am using CherryPy to serve my application in multiple ports say 8080 and 8081
cherrypy.server.unsubscribe()
for port in [8080, 8081]:
server = Server()
server.socket_port = port
server.socket_host = "0.0.0.0"
server.thread_pool = 100
server.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()
With this the application is being served as expected on both the ports. Now due to some reason I want to stop the server of a specific port and other being served normally. When I stop the process on a particular port with the following command,
fuser -k "$port"/tcp
All the process on the ports in which the application was started (8080, 8081) are also being killed. Is this an expected behaviour ?
If yes, is there anyway I can achieve serving the application independently without affecting the other ports on which it is running ? (Other than like I should change the port in the source code and run it again manually)
If no, what is the mistake I am doing here ?
Any help would be appreciated!

How to configure apache to support websockets

I wrote server in python and now I would like to configure apache web server to support websockets.
My server returns information when a client sends queries to these addresses:
def make_app():
return tornado.web.Application([
(r"/playgame", EmptyGame),
(r"/playgame/", EmptyGame),
(r"/playgame/(.*)", PlayerGameWebsocket)
])
How to configure the server to support regular user traffic but also to enable websockets when the client establishes such a connection?
I user apache2.4 server.
Ok, it turned out that the solution is trivial. If someone ever looked for an answer, just add a simple redirection to the application in the virtual host configuration which listens on localhost:
ProxyPassMatch "/playgame/(.*)" "ws://127.0.0.1:8888/playgame/$1"
ProxyPassReverse "/playgame/(.*)" "ws://127.0.0.1:8888/playgame/$1"
Thanks to such syntax, we can even pass additional data, e.g. "/playgame/123".
We connect from the client without specifying the port:
var adr = "ws://serverip/playgame/" + gameid;
var ws = new WebSocket(adr);

504 Connection Error Flask Nginx uWSGI Ubuntu

Hello all I was hoping I could receive some guidance on this matter.
I have a flask application that is setup on an ubuntu server. It uses ssh to create a tunnel to a Centos 7 Server that has it's mysql database. Upon running this application with python on the Ubuntu Server I'm able to perfectly login to my application and view data from database from domain ip. Now upon trying to run the application on nginx and uWSGI I can actually get to the login page from my domain name. But upon entering my credentials and trying to login, the page loads for around a minute and the I receive the 504 Connection Time Out Error
Would I be receiving this because my application is trying to reach out to another server while processing data from me. I'm not sure and nothing has been a help yet. Here are my files
server block
server {
listen 80;
server_name itinareport.tk www.itinareport.tk;
location / {
uwsgi_read_timeout 600;
include uwsgi_params;
uwsgi_pass unix:/home/pinchrep2/itinarep/itinarep.sock;
}
}
ini file
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = itinarep.sock
chmod-socket = 660
vacuum = true
die-on-term=true
wsgi.py
from main import app
if __name__ == "__main__":
app.run()
service file
[Unit]
Description=uWSGI instance to serve itinarep
After=network.target
[Service]
User=pinchrep2
Group=www-data
WorkingDirectory=/home/pinchrep2/itinarep
Environment="PATH=/home/pinchrep2/itinarep/it_venv/bin"
ExecStart=/home/pinchrep2/itinarep/it_venv/bin/uwsgi --ini itinarep.ini
[Install]
WantedBy=multi-user.target
Here is where I ssh from main py file
main.py
sshforward = SSHTunnelForwarder(
("public ip", 22),
ssh_username = 'user',
ssh_password = 'pass',
remote_bind_address = ('127.0.0.1', 3306)
)
sshforward.start()
local_port = sshforward.local_bind_port
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://root#localhost:{local_port}/asteriskcdrdb"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Again I just need this to be deployed. Please point in the right direction configuration wise. I can get to application but as soon as logging in I receive this issue.
When your database connection url references "localhost", its really connecting via a unix socket.
You can connnect using a local_bind_address containing a unix socket adding ?unix_socket=/path/to/mysql.sock to the SQLALCHEMY_DATABASE_URI like this answer.
Seems connecting to a remote unix socket is waiting for this upstream issue to be implemented.

Problems with external visibility of Flask web-server

I have managed to to install flask and run the hello-world script:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
I was impressed how easy it was. Then I wanted to make my web-server visible externally. As recommended, I put host='0.0.0.0' as the argument of run function. Then I found my IP address (in Google) and put it in the address line of my web browser (while the hello-world-script was running).
As a result I got: "A username and password are being requested" and a dialogue box where I need to put a user name and password. I am not sure but I think it comes from my wireless network. Is there a way to change this behaviour?
How are you trying to run your application? If you run flask as app.run() - flask creates its own WSGI server on your host (by default 127.0.0.1) and port (by default 5000) (need permissions if port < 1000). If you run flask using nginx + WSGI or etc. your server resolves host and port.
Now it looks like you want get application by port which resolved your server like nginx or Apache. Try to get flask application by http://your-server-host-or-ip:5000 with the default port or try to change the port (set explicit) like app.run('0.0.0.0', 8080) and get it by http://your-server-host-or-ip:8080.
By the way, you can always get IP address using command-line tools e.g. ifconfig for Unix-like systems, or ipconfig /all for Windows.
To elaborate a little bit onto what #tbicr said, that password prompt indicates that you're trying to connect to your IP on port 80, which is most likely hosting an administration page for your router/modem. You want to connect to your IP on port 5000, the default port for Flask apps run with app.run().

Categories

Resources