flask app won't run on ubuntu 12.04 (digital ocean) - python

I am having difficulties deploying a basic flask app on a digital ocean server running ubuntu 12.04, apache2, and mod-wsgi. I have tried a number of different modifications of both the myapp.conf file and the myapp.wsgi file. I suspected that these were the culprits, but now I'm not so sure.
At all times, visiting my url just displays the apache 'It works' dialogue. Each attempt made to successfully restart the apache service (after trying to fix the problem), and access the website sees this same activity in the error.log:
[Wed Aug 27 00:49:14 2014] [notice] caught SIGTERM, shutting down
[Wed Aug 27 00:49:15 2014] [notice] Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured -- resuming normal operations
And this activity in the access.log:
11.22.33.44 - - [27/Aug/2014:00:49:19 -0400] "GET / HTTP/1.1" 304 209 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
11.22.33.44 - - [27/Aug/2014:00:49:21 -0400] "GET / HTTP/1.1" 304 208 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
11.22.33.44 - - [27/Aug/2014:00:49:24 -0400] "GET / HTTP/1.1" 304 208 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
By 'basic' flask app, I mean: no sql database (as in none, not as in non-relational), no site users, no factory, no blueprint, etc.
The relevant directory /var/www/myapp/ looks like this (using virtualenv to run the app):
myapp/
+ myapp/
| + static/
| + templates/
| + venv/
| | __init__.py
| myapp.wsgi
Although I have tried several versions of the myapp.conf file, these two are representative:
<VirtualHost *:80>
ServerName myapp.com
WSGIDaemonProcess myapp user=flask group=www-data home=/var/www/myapp/
WSGIScriptAlias / /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp/myapp/>
WSGIProcessGroup myapp
WSGIApplicationGroup % {GLOBAL}
WSGIScriptReloading On
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
And:
<VirtualHost *:80>
ServerName myapp.com
WSGIScriptAlias / /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp/myapp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/myapp/myapp/static
<Directory /var/www/myapp/myapp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
The two general types of myapp.wsgi files I have tried are:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/myapp/")
from myapp import app as application
And:
activate_this = '/var/www/myapp/myapp/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import os
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/var/www/myapp/')
from myapp import app as application
#commenting out same in __init__.py
if __name__ == '__main__':
application.run()
The app does run successfully on my local machine, and I always chowned the /var/www/ directory for each user identified in the .conf file.
Any thoughts, tips, pointers, etc are extraordinarily welcome. Thanks very kindly.

Related

Issues getting nginx to serve my flask app

The bounty expires in 4 days. Answers to this question are eligible for a +350 reputation bounty.
dms_quant wants to draw more attention to this question.
I have a flask app that I would like to serve via a DO Droplet.
I have followed How To Serve Flask Applications with Gunicorn and Nginx on Ubuntu 22.04
This is my folder structure
root/
└── baseweb/
├── venv
├── app.py
└── app/
├── routes.py
└── templates/
└── index.html
app.py looks like this
from app import app
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
I have created a baseweb service
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/baseweb
Environment="PATH=/root/baseweb/venv/bin"
ExecStart=/root/baseweb/venv/bin/gunicorn --workers 1 --bind unix:baseweb.sock app:app
[Install]
WantedBy=multi-user.target
and my nginx configuration (/etc/nginx/sites-available/baseweb) - edited per arthur simas comment below
server {
listen 80;
server_name baserank.net www.baserank.net;
location / {
proxy_pass http://unix:/root/baseweb/baseweb.sock;
}
}
When i simply run app.py using my venv, i can access my flask app via http://68.183.68.148:5000/
if I run gunicorn --bind 0.0.0.0:5000 app:app i can also access my app via the same IP.
But when i try to access via nginx (via http://68.183.68.148 without running the app in console), i get
502 Bad Gateway
nginx/1.22.0 (Ubuntu)
I have spent hours trying to adjust settings, but i have no idea where this is going wrong - so any help is very much appreciated.
Edit 2023-02-17: Ngnix access.log
185.16.141.5 - - [17/Feb/2023:14:14:17 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:17 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:20 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:20 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
143.110.222.166 - - [17/Feb/2023:14:22:21 +0000] "GET / HTTP/1.1" 502 166 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1"
your ngnix config is wrong. you don't use root directive for reverse proxying with nginx, but instead proxy_pass. the tutorial you've posted is right. the changes you should do:
server {
listen 80;
server_name your_domain www.your_domain; # place here your website domain (optional directive)
location / {
proxy_pass http://unix:/root/baseweb/baseweb.sock;
}
}
listen tells were the nginx server should listen to requests. it could be only the port (80), ip:port (68.183.68.148:80), an unix socket (unix:/var/run/nginx.sock), etc...
the proxy_pass directive acts as a reverse proxy, forwarding traffic to the provided URL.
root is for serving static files.
read more at:
NGINX Module ngx_http_core_module - listen
NGINX Reverse Proxy
NGINX Module ngx_http_proxy_module - proxy_pass
Serving Static Content
also, be sure to create the service in systemd, at the correct path location and check if its running sudo systemctl status myproject (or nginx would not be able to forward traffic to it)
One potential issue could be with the ownership and permission of the socket file /root/baseweb/baseweb.sock. Make sure the user running the Gunicorn service (in your case, root) has ownership of the file, and the permissions are set correctly. You can try changing the group to root in the baseweb.service file:
[Service]
User=root
Group=root
WorkingDirectory=/root/baseweb
Environment="PATH=/root/baseweb/venv/bin"
ExecStart=/root/baseweb/venv/bin/gunicorn --workers 1 --bind unix:baseweb.sock app:app
After modifying the service file, make sure to reload the daemon and restart the service:
sudo systemctl daemon-reload
sudo systemctl restart baseweb
You can also check the error log of Gunicorn by adding --log-level debug --error-logfile /path/to/error.log to the Gunicorn command in the baseweb.service file. Then, check the content of /path/to/error.log for more details about the error.
Another thing to try is to update the Nginx configuration to proxy pass to http://127.0.0.1:5000 instead of the socket file. You can try modifying the configuration file as follows:
server {
listen 80;
server_name baserank.net www.baserank.net;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
After modifying the configuration file, restart the Nginx service:
sudo systemctl restart nginx

mod_wsgi Call to fopen() failed for 'path/wsgi.py apache ubuntu

hi i try to deploy my django project 2.2v on ubuntu apache server
when i run cat /var/log/apache2/error.log i get this error:
[time] [wsgi:error] [pid 13224:tid 2323232] (13)Permission denied: [remote some number:number] mod_wsgi (pid=13323, process='django_app', application='django_project|'): Call to fopen() failed for '/root/project_name/project_name/wsgi.py'.
my wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zettapc.settings')
application = get_wsgi_application()
This is my /etc/apache2/sites-available/django_proj.conf :
<VirtualHost *:80>
Alias /static /root/project_name/static
<Directory /root/project_name/static>
Require all granted
</Directory>
Alias /meida /root/project_name/meida
<Directory /root/project_name/meida>
Require all granted
</Directory>
<Directory /root/project_name/zettapc>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /root/project_name/project_name/wsgi.py
WSGIDaemonProcess django_app python-path=/root/project_name python-home=/root/project_name/venv/
WSGIProcessGroup django_app
</VirtualHost>
and output of on my browser is :
Internal Server Error
this the output of ps aux | egrep '(apache|httpd)'
and output of ls -l /root/project_name/project_name/wsgi.py is:
-rwxr-x--- 1 root root 177 time /root/project_name/project_name/wsgi.py
is there something i've missed
Most likely your wsgi file is owned by root and apache server runs as a non-root user.
You can check which user your apache servers runs as with ps aux | egrep '(apache|httpd)'
and which user owns your wsgi file with ls -l /root/project_name/project_name/wsgi.py
You best bet would be to move your project from the root folder to somwhere more appropriate (for example /usr/) and change it's owner using chown -r <user>:<user> <folder>
Alternatively run apache server as root but it's a really bad practice so don't do that.
edit:
It might also be that your wsgi server (gunicorn/uwsgi ?) runs as the wrong user, the same fix still does the trick.

Deploying a Flask application using cgi script in Xampp

I am attempting to deploy a simple Hello World script on XAMMP.
In case the link is removed here is application.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
My applciation.cgi script is as follows:
#!C:/Users/Simon/Documents/Python/Scripts/python.exe
from wsgiref.handlers import CGIHandler
from application import hello
CGIHandler().run(app)
C:/Users/Simon/Documents/Python/ is the location of my virtual python environment.
I have configured XAMMP (httpd.conf) in the following way:
AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict
This configuration I kept in all cases.
I tried the following as suggested in the documentation:
ScriptAlias /Network C:/Users/Simon/Documents/Network/application.cgi
This failed and I tried this as suggested in here:
<Directory "C:/Users/Simon/Documents/Network">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
Alias /Network "C:/Users/Simon/Documents/Network"
In all cases an Error 500 Server error! was returned.
I'm not sure if it's needed but here is the relevant error showing in access.log:
192.168.0.8 - - [17/Feb/2018:13:21:12 +0000] "GET / HTTP/1.1" 500 1100 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36"
If anything is missing please tell me and I will add it.
How can I correctly configure my server so that I can run this script?
There was mistake in application.cgi:
#!C:/Users/Simon/Documents/Python/Scripts/python.exe
from wsgiref.handlers import CGIHandler
from application import hello
CGIHandler().run(hello)
It is however still returning an error:
A server error occurred. Please contact the administrator.
You've imported the wrong thing in your CGI script; as a result app is not defined. You should be importing that rather than hello.

How can I run django using apache2?

I'm trying to run django on apache2 using mod_wsgi, but when I'm trying to connect "locatoka.ru" I get "Forbidden You don't have permission to access / on this server."
My actions:
I added to httpd.conf
LoadModule wsgi_module /usr/local/Cellar/mod_wsgi/3.2/libexec/mod_wsgi.so
changed httpd.conf
WSGIScriptAlias / /Users/Loginov/Desktop/project/project/wsgi.py
<VirtualHost locatoka.ru:80>
ServerName locatoka.ru
ServerAlias www.locatoka.ru
DocumentRoot "/Users/Loginov/Desktop/project"
<Directory /Users/Loginov/Desktop/project/project>
<Files wsgi.py>
Order deny,allow
Require all granted
</Files>
</Directory>
</VirtualHost>
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = get_wsgi_application()
I'm using Mac OS X El Capitan and Python3.

How to correctly deploy a flask application with mod_wsgi on Apache2.2

I have been trying to deploy my application on Ubuntu web server but with limited success. The virtual host file defined by me is :
#WSGIRestrictStdout Off
<VirtualHost *:80>
ServerName demo.engineerinme.com
WSGIDaemonProcess fedoracollege user=engineer group=www-data threads=5
WSGIScriptAlias / /home/engineer/fedora-college/fedora_college.wsgi
<Directory /home/engineer/fedora-college/>
WSGIProcessGroup fedoracollege
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Options All ExecCGI Indexes FollowSymLinks
Order allow,deny
Allow from all
</Directory>
Alias /static /home/engineer/fedora-college/fedora_college/static
<Directory /home/engineer/fedora-college/fedora_college/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel debug
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
The problem I am facing is that , the static content is working correctly but the flask application is not running. Like http://demo.engineerinme.com shows a not found error. But the http://demo.engineerinme.com/static works.
The wsgi script for the deployment is :
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/home/engineer/fedora-college/")
from fedora_college import app as application
application.secret_key = 'Add your secret key'
Error Log :
[Mon Jun 30 23:01:31 2014] [debug] mod_deflate.c(615): [client 59.177.114.30] Zlib: Compressed 233 to 180 : URL /
[Mon Jun 30 23:01:32 2014] [debug] mod_deflate.c(615): [client 59.177.114.30] Zlib: Compressed 233 to 180 : URL /
[Mon Jun 30 23:01:51 2014] [debug] mod_deflate.c(615): [client 59.177.114.30] Zlib: Compressed 233 to 180 : URL /
Access.log
59.177.114.30 - - [30/Jun/2014:23:01:32 +0400] "GET / HTTP/1.1" 404 441 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36"
59.177.114.30 - - [30/Jun/2014:23:01:51 +0400] "GET / HTTP/1.1" 404 442 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36"
The code for the application is present here :https://github.com/hammadhaleem/fedora-college/
Any help with possible deployment would be highly appreciated.
Thanks
I faced this problem and the solution for the same was in the virtual host file.
Also sometimes the Apache logs showed this error:
[Mon Oct 17 15:24:24 2011] [error] [client 90.181.85.69] (13)Permission denied: mod_wsgi (pid=21805): Unable to connect to WSGI daemon process 'fedoracollege' on '/var/run/apache2/wsgi.16282.4.1.sock' after multiple attempts.
This problem has been explained here properly. I just rebuilt the wsgi_mod.
https://serverfault.com/questions/322131/wsgi-says-permissions-denied-on-my-ubuntu-server-no-wsgisocketprefix-setting
Also, rewriting the virtual host file to this format. (Removing virtualhost and direcory tags)
Alias /static /home/engineer/fedora-college/fedora_college/static
WSGIDaemonProcess fedoracollege user=engineer group=www-data threads=5
#WSGIDaemonProcess fedoracollege maximum-requests=1000 display-name=fedora-college processes=4 threads=4
WSGISocketPrefix /var/run/wsgi
WSGIRestrictStdout Off
WSGIRestrictSignal Off
WSGIPythonOptimize 1
WSGIScriptAlias / /home/engineer/fedora-college/fedora_college.wsgi
<Location />
WSGIProcessGroup fedoracollege
</Location>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel debug
CustomLog ${APACHE_LOG_DIR}/access.log combined
Also, set the
application = True
For proper error reporting.
Hope this helps someone. (Don't forget to upvote :P )
Thanks for all your help.

Categories

Resources