configuring Nginx to run flask automatically with uwsgi - python

I am developing python programs and I have a flask file which runs them. Now I am trying to run flask automatically from Nginx and linking them with uWSGI. It's not working and getting stuck.
I followed this page.here is the link: https://vladikk.com/2013/09/12/serving-flask-with-nginx-on-ubuntu/
I have performed all the necessary steps and got 502 bad gateway error.
while executing
uswgi --ini /var/www/tg/tg_uswgi.ini
I am getting the following
[uSWGI] getting INI configuration from /var/www/tg/tg_uwsgi.ini
after this, I am not getting anything.when i run my server, it still gives me 502 Bad gateway.
this is my
tg_nginx.conf
server {
listen 80;
server_name localhost;
charset utf-8;
client_max_body_size 75M;
location / { try_files $uri #yourapplication; }
location #yourapplication {
include uwsgi_params;
uwsgi_pass unix:/var/www/tg/tg_uwsgi.sock;
}
}
this is my tg_uwsgi.ini
[uwsgi]
#application's base folder
base = /var/www/tg
#python module to import
app = fileforflk //fileforflk is my flask file which calls other python
//files
module = %(app)
home = %(base)/venv
pythonpath = %(base)
#socket file's location
socket = /var/www/demoapp/%n.sock
#permissions for the socket file
chmod-socket = 666
#the variable that holds a flask application inside the module imported at line #6
callable = app
#location of log files
logto = /var/log/uwsgi/%n.log
this is my flask file
from flask import Flask
import browser //python file the flask is calling
app = Flask(_name_)
#app.route('/test',methods= ['GET'])
def result():
return ("success")
if _name_ == '_main_':
app.run(host = '0.0.0.0',port=5000)
After getting INI configuration, the terminal is not showing anything and the server still returns bad gateway. please help me with this.

You should define:
socket = /var/www/demoapp/%n.sock
And :
uwsgi_pass unix:/var/www/tg/tg_uwsgi.sock;
should be matching. So for example, define:
socket = /var/www/tg/%n.sock
And :
sudo chown -R www-data:www-data /var/www/tg/
sudo chown -R www-data:www-data /var/log/uwsgi/

Related

I am working on a web app using Django, running on Nginx, and I am getting 111 connection refused, and I cant work out why

I have previously configured an app in the exact same way but when I updated Ubuntu, I broke my python install. I fixed python, and tried to set up another app in the exact same way, using the same tutorials, but I am getting a 111 error when I try to connect. I can connect if I run the app using gunicorn (which I only tried because it wasn't working using nginx), but I want to find the problem and fix it. As far as I can see everything is configured according to the documentation I went through.
Here is the uwsgi config file
# glossbox_uwsgi.ini file
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /usr/local/apps/glossbox/glossbox
# Django's wsgi file
wsgi-file = /usr/local/apps/glossbox/glossbox/glossbox/wsgi.py
# the virtualenv (full path)
home = /usr/local/apps/glossbox/venv
plugins = python
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = server 127.0.0.1:8001
# ... with appropriate permissions - may be needed
chmod-socket = 664
clear environment on exit
vacuum = true
here is the nginx conf file:
# glossbox_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///path/to/your/mysite/mysite.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name vps746196.ovh.net; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias /usr/local/apps/glossbox/glossbox/media; # your Django project's media files - amend as required
}
location /static {
alias /usr/local/apps/glossbox/glossbox/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /usr/local/apps/glossbox/glossbox/uwsgi_params; # the uwsgi_params file you installed
}
}
the app runs using the command 'uwsgi --ini glossbox_uwsgi.ini' but I get 111 connection refused when I try to connect.
I tried to run using 'gunicorn glossbox.wsgi:application --bind 0.0.0.0:8000' just to see if it worked, and it did, although site couldn't find the static files for the admin site, I assume that is down to me having no configuration set up for gunicorn. Either way, I need to find out why it is refusing the connection.
Any help will be appreciated :-)

Flask+nginx+uwsgi: only serve url with nginx if flask doesn't have a route for it

nginx config for the server (the main nginx one is the default one on debian 9):
server {
listen 80;
server_name subdomain.domain.com;
include /etc/nginx/mime.types;
location /galleries {
autoindex on;
alias /srv/galleries/;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/tmp/scraper.sock;
}
}
uwsgi config:
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = /tmp/scraper.sock
chmod-socket = 777
uid = www-data
gid = www-data
vacuum = true
die-on-term = true
plugins = python3
py-autoreload = 1
If I try creating a route for /galleries/whatever, ie like this:
#app.route("/galleries/whatever")
def test():
return "Hello"
I'll just see the indexed files inside /galleries/whatever through nginx instead of going through flask.
Is there a way for me to force nginx to only handle requests if flask returns 404? Alternatively, is there a better way for me to serve files while still having them available under those urls? Keep in mind the /galleries folder is pretty big and generated by another program.
I run the server with "uwsgi --ini server.ini" and nothing else.

uwsgi mountpoints issue: RuntimeError: class.__dict__ not accessible in restricted mode

Pyramid application throws RuntimeError: class.__dict__ not accessible in restricted mode into python2.7/site-packages/zope/interface/declarations.py while gets request from nginx by uwsgi. In this case uses uwsgi mount point configuration. Without mount point - no errors.
Have following configuration based on nginx + uwsgi + pyramid + supervisor:
Pyramid configuration ini file:
[uwsgi]
socket = PATH_TO_SOCK
virtualenv = PATH_TO_VIRTUALENV
module = MODULE_NAME
mount = /URL_SUB_PATH=MODULE_NAME/uwsgiapp.py
manage-script-name = true
env = PASTE_CONFIG=%p
uwsgi.py:
from paste.deploy import loadapp
app = loadapp('config:' + os.environ['PASTE_CONFIG'])
def application(environ, start_response):
if os.environ.get('WSGI_FILE_WRAPPER', 'yes').lower() in ('no', 'false'):
environ.pop('wsgi.file_wrapper', None)
return app(environ, start_response)
command for run from supervisor.conf:
command=PATH_TO_VIRTUALENV/bin/uwsgi --ini-paste PATH_TO_PYRAMID_CONF_INI
and fragment of nginx config:
upstream UPSTREAM_NAME {
server unix:///PATH_TO_SOCK;
}
location /URL_SUB_PATH/ {
uwsgi_pass UPSTREAM_NAME;
include uwsgi_params;
}
What is the reason for this unexpected behavior?

Serving flask app on subdirectory nginx + uwsgi

I am try to deploy flask on a sub directory on my website, this script is super light weight and doesn't need (actually it can't) to roll into the main project. How ever when I go to the end point, I get a 404 error from flask (can confirm that it is flask because the log shows activity). I am passing uwsgi_param SCRIPT_NAME /upload; and uwsgi_modifier1 30; in my nginx config file, but that doesn't seem to work. How can I get uwsgi to serve my flask application on an nginx sub location (subdir)?
Here is my nginx config (the /upload location is where the trouble is):
upstream django {
server app0.api.xyz.com:9002;
}
server {
listen 443;
ssl on;
ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/api_xyz.key;
charset utf-8;
server_name dev.api.xyz.com;
location / {
uwsgi_pass django;
include /etc/nginx/uwsgi_params;
}
location /media {
alias /var/xyzdata;
}
location /upload {
include /etc/nginx/uwsgi_params;
uwsgi_pass unix:/var/sockets/upload.sock;
uwsgi_param SCRIPT_NAME /upload;
uwsgi_modifier1 30;
}
}
my uwsgi.ini file:
[uwsgi]
chdir = /home/ubuntu/uploadFlask
module = images
callable = app
socket = /var/sockets/upload.sock
master = true
processes = 10
vacuum = true
uid = www-data
gid = www-data
daemonize = /var/log/uploads/error.log
and finally my entire flask app:
import os
from flask import Flask, request, redirect, url_for,Response, jsonify
from werkzeug import secure_filename
import time
UPLOAD_FOLDER = '/var/xyzdata'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DEBUG'] = True
#app.route('/<user>', methods=['POST'])
def upload_file(user):
file = request.files['file']
if file:
file_id = str(time.time()).replace('.','_')
filename = "{0}/images/{1}.jpg".format(user, file_id)
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
file.save(path)
return jsonify(physical_path=path, virtual_path=filename,
id=file_id)
#app.route('/delete/<user>/<id>/', methods=['POST'])
def delete_file(user, id):
pass
the point of this script is to upload images to my static server. My actual application sits on a separate server and thats why this can't sit there.
Basically what i want is to be able to go to dev.api.xyz.com/upload/123/ and hit upload_file. I'm expecting a 405 error in the browser, because it is restricted to POST. But I am getting a 404 error. Here is a sample output from the flask/uwsgi log:
[pid: 27900|app: 0|req: 4/5] 50.199.33.84 () {40 vars in 669 bytes} [Wed Jul 1 01:03:51 2015] GET /upload/things#things.com => generated 233 bytes in 0 msecs (HTTP/1.1 404) 2 headers in 72 bytes (1 switches on core 0)
So flask is getting hit but the url matching is not working. Thanks in advance for your help.
The best solution I've found so far would be using the mount option of uwsgi. In your config add the line
mount = /upload=<scriptname>
Solution courtesy of https://serverfault.com/questions/461946
Best and quick solution for me
location ~ /upload(/.*) {
include /etc/nginx/uwsgi_params;
uwsgi_pass unix:/var/sockets/upload.sock;
uwsgi_param PATH_INFO "$1";
}
Hope this can help you. cheers

nginx + uwsgi for multiple sites using multiple ports

I would like to host 2 sites in one IP address 1.2.3.4 for example. I want to visit them by using different ports. For example, I would like to have 1.2.3.4:8000 for siteA, while 1.2.3.4:9000 to point to siteB. I am using nginx + uwsgi.
Here is the example to configure one of sites.
For NGINX, I had:
server {
listen 8000; ## listen for ipv4; this line is default and implied
location / {
uwsgi_pass unix:///tmp/uwsgi.sock;
include uwsgi_params;
uwsgi_read_timeout 1800;
}
}
For UWSGI, I had:
[uwsgi]
socket = /tmp/uwsgi.sock
master = true
harakiri = 60
listen = 5000
limit-as = 512
reload-on-as = 500
reload-on-rss = 500
pidfile = /tmp/uwsgi.pid
daemonize = /tmp/uwsgi.log
**chdir = /home/siteA**
module = wsgi_app
plugins = python
To visit siteA, I simple go to 1.2.3.4:8000.
I have no problem with configuration of one site, but I have no idea to make it working with two sites.
Please note that I didnot bind the site with the server name. Does it matter?
Thanks in advance.
P.S. The following is the way I launch NGINX and UWSGI.
I first put the nginx conf file (for siteA, I called it as siteA_for_ngxing.conf) in the /etc/nginx/sites-available/ directory.
I then use uwsgi --ini uwsgi.ini to start uwsgi. (the file of uwsgi.ini contains the above [uwsgi])...
Any help?
The following example might be useless for you, because it seems you installed uWSGI manually, instead of using system repository. But I think, you can easly find how uWSGI is configured on Ubuntu and make the same configuration on your system.
Here how I have done it on Ubuntu. I installed both uWSGI and nginx from Ubuntu repo, so I got the following dirs:
/etc/nginx/sites-available
/etc/nginx/sites-enabled
/etc/uwsgi/apps-available
/etc/uwsgi/apps-enabled
On /etc/uwsgi/apps-available I placed two files: app_a.ini and app_b.ini. There is no option socket (as well as pid and daemonize) in these files. uWSGI will detect socket, log, and pid file names using ini-file name. Then I created symlink to these files in /etc/uwsgi/apps-enabled to enable apps.
For nginx I used /etc/nginx/sites-available/default config file (it already symlinked to enabled dir).
upstream app_a {
server unix:///run/uwsgi/app/app_a/socket;
}
upstream app_b {
server unix:///run/uwsgi/app/app_b/socket;
}
server {
listen 8000;
location / {
uwsgi_pass app_a;
include uwsgi_params;
}
}
server {
listen 9000;
location / {
uwsgi_pass app_b;
include uwsgi_params;
}
}

Categories