Tutorial

How To Serve Flask Applications with uWSGI and Nginx on Ubuntu 14.04

How To Serve Flask Applications with uWSGI and Nginx on Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

In this guide, we will be setting up a simple Python application using the Flask micro-framework on Ubuntu 14.04. The bulk of this article will be about how to set up the uWSGI application server to launch the application and Nginx to act as a front end reverse proxy.

Prerequisites

Before starting on this guide, you should have a non-root user configured on your server. This user needs to have sudo privileges so that it can perform administrative functions. To learn how to set this up, follow our initial server setup guide.

To learn more about uWSGI, our application server and the WSGI specification, you can read the linked section of this guide. Understanding these concepts will make this guide easier to follow.

When you are ready to continue, read on.

Install the Components from the Ubuntu Repositories

Our first step will be to install all of the pieces that we need from the repositories. We will install pip, the Python package manager, in order to install and manage our Python components. We will also get the Python development files needed to build uWSGI and we’ll install Nginx now as well.

Update your local package index and then install the packages by typing:

sudo apt-get update
sudo apt-get install python-pip python-dev nginx

Create a Python Virtual Environment

Next, we’ll set up a virtual environment in order to isolate our Flask application from the other Python files on the system.

Start by installing the virtualenv package using pip:

sudo pip install virtualenv

Now, we can make a parent directory for our Flask project. Move into the directory after you create it:

mkdir ~/myproject
cd ~/myproject

We can create a virtual environment to store our Flask project’s Python requirements by typing:

virtualenv myprojectenv

This will install a local copy of Python and pip into a directory called myprojectenv within your project directory.

Before we install applications within the virtual environment, we need to activate it. You can do so by typing:

source myprojectenv/bin/activate

Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (myprojectenv)user@host:~/myproject$.

Set Up a Flask Application

Now that you are in your virtual environment, we can install Flask and uWSGI and get started on designing our application:

Install Flask and uWSGI

We can use the local instance of pip to install Flask and uWSGI. Type the following commands to get these two components:

pip install uwsgi flask

Create a Sample App

Now that we have Flask available, we can create a simple application. Flask is a micro-framework. It does not include many of the tools that more full-featured frameworks might, and exists mainly as a module that you can import into your projects to assist you in initializing a web application.

While your application might be more complex, we’ll create our Flask app in a single file, which we will call myproject.py:

nano ~/myproject/myproject.py

Within this file, we’ll place our application code. Basically, we need to import flask and instantiate a Flask object. We can use this to define the functions that should be run when a specific route is requested. We’ll call our Flask application in the code application to replicate the examples you’d find in the WSGI specification:

from flask import Flask
application = Flask(__name__)

@application.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

This basically defines what content to present when the root domain is accessed. Save and close the file when you’re finished.

You can test your Flask app by typing:

python myproject.py

Visit your server’s domain name or IP address followed by the port number specified in the terminal output (most likely :5000) in your web browser. You should see something like this:

Flask sample app

When you are finished, hit CTRL-C in your terminal window a few times to stop the Flask development server.

Create the WSGI Entry Point

Next, we’ll create a file that will serve as the entry point for our application. This will tell our uWSGI server how to interact with the application.

We will call the file wsgi.py:

nano ~/myproject/wsgi.py

The file is incredibly simple, we can simply import the Flask instance from our application and then run it:

from myproject import application

if __name__ == "__main__":
    application.run()

Save and close the file when you are finished.

Configure uWSGI

Our application is now written and our entry point established. We can now move on to uWSGI.

Testing uWSGI Serving

The first thing we will do is test to make sure that uWSGI can serve our application.

We can do this by simply passing it the name of our entry point. We’ll also specify the socket so that it will be started on a publicly available interface and the protocol so that it will use HTTP instead of the uwsgi binary protocol:

uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi

If you visit your server’s domain name or IP address with :8000 appended to the end in your web browser, you should see a page that looks like this:

Flask sample app

When you have confirmed that it’s functioning properly, press CTRL-C in your terminal window.

We’re now done with our virtual environment, so we can deactivate it:

deactivate

Any operations now will be done to the system’s Python environment.

Creating a uWSGI Configuration File

We have tested that uWSGI is able to serve our application, but we want something more robust for long-term usage. We can create a uWSGI configuration file with the options we want.

Let’s place that in our project directory and call it myproject.ini:

nano ~/myproject/myproject.ini

Inside, we will start off with the [uwsgi] header so that uWSGI knows to apply the settings. We’ll specify the module by referring to our wsgi.py file, minus the extension:

[uwsgi]
module = wsgi

Next, we’ll tell uWSGI to start up in master mode and spawn five worker processes to serve actual requests:

[uwsgi]
module = wsgi

master = true
processes = 5

When we were testing, we exposed uWSGI on a network port. However, we’re going to be using Nginx to handle actual client connections, which will then pass requests to uWSGI. Since these components are operating on the same computer, a Unix socket is preferred because it is more secure and faster. We’ll call the socket myproject.sock and place it in this directory.

We’ll also have to change the permissions on the socket. We’ll be giving the Nginx group ownership of the uWSGI process later on, so we need to make sure the group owner of the socket can read information from it and write to it. We will also clean up the socket when the process stops by adding the “vacuum” option:

[uwsgi]
module = wsgi

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

The last thing we need to do is set the die-on-term option. This is needed because the Upstart init system and uWSGI have different ideas on what different process signals should mean. Setting this aligns the two system components, implementing the expected behavior:

[uwsgi]
module = wsgi

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

die-on-term = true

You may have noticed that we did not specify a protocol like we did from the command line. That is because by default, uWSGI speaks using the uwsgi protocol, a fast binary protocol designed to communicate with other servers. Nginx can speak this protocol natively, so it’s better to use this than to force communication by HTTP.

When you are finished, save and close the file.

Create an Upstart Script

The next piece we need to take care of is the Upstart script. Creating an Upstart script will allow Ubuntu’s init system to automatically start uWSGI and serve our Flask application whenever the server boots.

Create a script file ending with .conf within the /etc/init directory to begin:

sudo nano /etc/init/myproject.conf

Inside, we’ll start with a simple description of the script’s purpose. Immediately afterwards, we’ll define the conditions where this script will be started and stopped by the system. The normal system runtime numbers are 2, 3, 4, and 5, so we’ll tell it to start our script when the system reaches one of those runlevels. We’ll tell it to stop on any other runlevel (such as when the server is rebooting, shutting down, or in single-user mode):

description "uWSGI server instance configured to serve myproject"

start on runlevel [2345]
stop on runlevel [!2345]

Next, we need to define the user and group that uWSGI should be run as. Our project files are all owned by our own user account, so we will set ourselves as the user to run. The Nginx server runs under the www-data group. We need Nginx to be able to read from and write to the socket file, so we’ll give this group ownership over the process:

description "uWSGI server instance configured to serve myproject"

start on runlevel [2345]
stop on runlevel [!2345]

setuid user
setgid www-data

Next, we need to set up the process so that it can correctly find our files and process them. We’ve installed all of our Python components into a virtual environment, so we need to set an environmental variable with this as our path. We also need to change to our project directory. Afterwards, we can simply call the uWSGI executable and pass it the configuration file we wrote:

description "uWSGI server instance configured to serve myproject"

start on runlevel [2345]
stop on runlevel [!2345]

setuid user
setgid www-data

env PATH=/home/user/myproject/myprojectenv/bin
chdir /home/user/myproject
exec uwsgi --ini myproject.ini

Save and close the file when you are finished.

You can start the process immediately by typing:

sudo start myproject

Configuring Nginx to Proxy Requests

Our uWSGI application server should now be up and running, waiting for requests on the socket file in the project directory. We need to configure Nginx to pass web requests to that socket using the uwsgi protocol.

Begin by creating a new server block configuration file in Nginx’s sites-available directory. We’ll simply call this myproject to keep in line with the rest of the guide:

sudo nano /etc/nginx/sites-available/myproject

Open up a server block and tell Nginx to listen on the default port 80. We also need to tell it to use this block for requests for our server’s domain name or IP address:

server {
    listen 80;
    server_name server_domain_or_IP;
}

The only other thing that we need to add is a location block that matches every request. Within this block, we’ll include the uwsgi_params file that specifies some general uWSGI parameters that need to be set. We’ll then pass the requests to the socket we defined using the uwsgi_pass directive:

server {
    listen 80;
    server_name server_domain_or_IP;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/user/myproject/myproject.sock;
    }
}

That’s actually all we need to serve our application. Save and close the file when you’re finished.

To enable the Nginx server block configuration we’ve just created, link the file to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

With the file in that directory, we can test for syntax errors by typing:

sudo nginx -t

If this returns without indicating any issues, we can restart the Nginx process to read the our new config:

sudo service nginx restart

You should now be able to go to your server’s domain name or IP address in your web browser and see your application:

Flask sample app

Conclusion

In this guide, we’ve created a simple Flask application within a Python virtual environment. We create a WSGI entry point so that any WSGI-capable application server can interface with it, and then configured the uWSGI app server to provide this function. Afterwards, we created an Upstart script to automatically launch the application server on boot. We created an Nginx server block that passes web client traffic to the application server, relaying external requests.

Flask is a very simple, but extremely flexible framework meant to provide your applications with functionality without being too restrictive about structure and design. You can use the general stack described in this guide to serve the flask applications that you design.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Justin Ellingwood
Justin Ellingwood
See author profile

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
75 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

On “Testing the uWSGI Serving”

when I try to use the command:

uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi

I get internal server error when I visit my VPS ip-addy at the port number.

In the terminal I get a slew of messages one of them being:

*** no app loaded. going in full dynamic mode ***

I can also only run python wsgi.py if I designate a host number (I put host=‘0.0.0.0’) in the app.run() call.

I’ve tried the command

uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi

both designating a host number in wsgi.py and without assigning a host number and I get an interneral server error with both ways

You need to specify that the callable is app, not application, as stated here: http://flask.pocoo.org/docs/0.10/deploying/uwsgi/#starting-your-app-with-uwsgi

What ended up working for me was uwsgi -s myproject.sock --http 0.0.0.0:8000 --module app --callable app (obviously in the directory with the .sock file). The app module and callable denote the name of the file with the definition of the Flask application as well as the variable of the application object itself.

you could also run it with: uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi:app

You should add supervisor to this tutorial. please and thanks

hi, thanks for this very good guide.

Inside myproject.ini you specify this permission :chmod-socket = 660

and on this guide https://www.digitalocean.com/community/tutorials/how-to-set-up-uwsgi-and-nginx-to-serve-python-apps-on-ubuntu-14-04

you specify this permission : chmod-socket = 664

What should I use 660 or 664 ?

thx

I am a beginner with respect to Python and Nginx.

In this tutorial, we are spawning 5 processes.

  1. So, will the Nginx spin up new processes to handle the load.?
  2. What kind of load can these processes handle?
  3. I am currently using Flask. Will Flask help me maintain heavy load? Or should I move to Django or some other frameworks?
Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
May 21, 2015

@anroopak: Hello. I don’t think I have all of the answers you’re looking for, but let me give it a try.

  1. Nginx will spin up the number of workers you specify in its configuration file (the worker_processes directive), which is completely separate from the uWSGI processes. uWSGI will take connections coming from Nginx and distribute them among the worker processes using its own algorithm. So the two worker configurations don’t have to match up.

  2. Each application will be different, so you will have to do load testing on your specific app to find out the best balance of resource usage and performance. Sadly, there isn’t really a good way to answer that one.

  3. If Flask suits your needs, then you can definitely keep using Flask. The choice of frameworks is often more about how you build your application than how it runs when you deploy. Flask is very light-weight as a framework, which means that it doesn’t impose too much structure on your project but doesn’t have all of the bells and whistles that something like Django has. The choice is mainly one of flexibility vs fast development rather than anything regarding performance.

I followed the instructions, however I am now getting a 502 Bad Gateway error when I access my server.

Looking at the nginx error logs the problem is :

2015/05/25 23:44:14 [crit] 6438#0: *1 connect() to unix:/root/wehate/wehate.sock failed (13: Permission denied) while connecting to upstream, client: 2.28.73.184, server: server_domain_or_ip, request: "GET $

I thought the point of doing ‘setgid www-data’ was to be able to access the sock. Is there something that should be added to the upstart script that isn’t included here?

Were you able to solve this? I am facing this same issue on my Ubuntu server, I have tried chmod a+rw on it, but still I get connection prematurely closed error

I am getting this error: unix:/home/mm/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream,

Any help, I followed the tutorial to the letter…

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
June 1, 2015

@monkmartinez: I just ran through the tutorial again to validate and I’m not seeing the problem you specified. Does the /home/mm/myproject/myproject.sock file exist? It is supposed to be created when you start the uWSGI process by typing:

sudo start myproject

If it is not creating that file, something is wrong. I’d suggest taking a look at the Upstart logs. Read the logs at /var/log/upstart/myproject.log. Does it contain any errors?

Make sure the permissions of your project directory are correct.

I too have permission problem it seems. When I run the script manually it works but when I use startup script then the server is unable to return correct data, instead I get 500 internal error.

This works: **uwsgi --ini myproject.ini **

This does not work: sudo start myproject

When you say that the project permission are correct what exactly do you men. My permission for the project are:

ls -lh drwxr-xr-x 6 user www-data 4.0K Sep 18 02:06 myproject

Is this correct?

I found adding the option (–chmod-socket=666) useful whether you start uwsgi manually or as a startup job. Otherwise, the socket file created lacks write access to the group and the others. After you do this, make sure to manually remove the socket file and restart uwsgi, so it creates a new one. Check the permissions (ls -l).

Besides the uwsgi error logs mentioned (/var/log/startup/uwsgi.log), also check nginx errors (/var/log/nginx/error.log).

I also found adding these two lines to the startup uwsgi.conf file useful:

  1. env PATH=/path/to/your/virtualenv/allthewayuptothe/bin
  2. chdir /path/to/your/project

Also, one thing I noticed. If the user/group set in uwsgi.conf file with setuid … and setgid … commands are not you, then start/stop uwsgi acts weird. You get “job not found” kind of error when you issue “stop uwsgi” command, whereas it is running. Seems like it filters it out because it seems to belong to another user.

Hi mmat, I do not have the folder /var/log/startup/uwsgi.log you are referring too. I got an internal error and looking to /var/log/upstart/monprojet.log, it writes “no python application found, check your startup logs for errors” How can I’ve access tot theses startup logs ?

Thanks for any help !

My apologies… It should have been upstart instead of startup :) E.g., /var/log/upstart/uwsgi.log

I had the same problem when typing “sudo start myproject” ,so I followed this link https://askubuntu.com/questions/614970/vivid-failed-to-connect-to-upstart-connection-refused .

sudo apt-get install upstart-sysv
sudo update-initramfs -u
sudo reboot

and now it works.

Please see my comment below that I made under @lekanovic’s post.

Hello, Thank you for this tutorial. All is working for me, but I can’t change the application name in wsgi.py and myproject.py if a replace “application” by “app” everywhere (like Flask’s homepage http://flask.pocoo.org/docs/0.10/quickstart/) I get an Internal Server Error. Even if a put debug=True in the application.run() I can’t have any explanation on what’s wrong.

I have exactly the same problem. Have you found a solution?

Hello, I followed this tutorial but am having problems. I posted the full explanation on Stack Overflow.

Can anyone here help?

i finish all steps under root and finally have Error 502 Bad Gateway

Can anyone here help?

Can you check the nginx logs at /var/log/nginx/error.log ?

Thanks i resolve problem self

Thanks for the tutorial Justin. Just a heads up to you and everyone else here; Not every single myproject is highlighted red. It’s easy to overlook and use Justin’s “myproject” instead of your own name. This lead to an issue where nginx would successfully run, but flask wouldn’t. So if you are encountering any issues, be sure to ctrl + f this page and ensure every “myproject” has been renamed to what you have.

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
August 13, 2015

@carlos7fd378f91: Thanks for the catch. I’ve updated the guide so that any instance within configuration files or commands is now highlighted. Thanks again!

Justin Thank you for the amazing tutorial!

There is a small typo in the block after this sentence: “Next, we’ll tell uWSGI to start up in master mode and spawn five worker processes to serve actual requests:”

It reads: module = uwsgi

and it should be: module = wsgi

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2015

@jarospirit: Thanks for catching that! Should be fixed now.

thanks for this nice tutorial.

but i have a problem with “start” command. when i type “sudo start myappname” on console then press enter, that message shown “start: Job failed to start”. i checked out log directory but there is also no file related my project. and i tried it with --verbose still there is no more information.

i solve this problem. when i setup my virtual env, i used that command “virtualenv -p python3 venv” for install python3.4 envirement. finally i removed it and setup again for python2.7 and everythink seems good. but i don’t know what i do when i want to use python3.4.

When I connect to my server I get: “Internal Server Error”

So when I try the command “python myproject.py” I can connect on port 5000 and I get the expected data. Then I close it with ctrl+c

The second command “uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi” works without problem. I can connect, but this time on port 8000 and I get the expected data. Then I close it with ctrl+c

When i start nginx and try to connect on port 80 I get “Internal Server Error”

I have double check all paths and they seem to be correct. There is also a myproject.sock created in root directory for the project. I can see that Its created by user and belongs to group www.data.

From “/var/log/nginx/error.log” I don’t seen any new errors only some previous error related to permission. First time I did this tutorial I was root user which I later changed.

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
September 15, 2015

@lekanovic: If you are getting an internal server error, it’s possible that your uwsgi Upstart configuration isn’t started or isn’t working correctly. You should try to start it again by typing:

  1. sudo start myproject

Where myproject is the name you gave the file you created in /etc/init ending in .conf. After you’ve tried starting the service, can you take a look at the Upstart logs? They’d be located at /var/log/upstart/myproject.log.

If that doesn’t point you to anything new, it might still be permissions/ownership issues.

Thanks jellingwood!

I managed to solve the problem by reading the log as you suggested. The problem was that my myproject.py we dependent on environment variables and did not start for that reason. In my code I had to chage os.environ[‘VAR’] to os.getenv(‘VAR’) to get it to work and pass down the variables.

When I try to “$ sudo start myproject” I get a “start: Job failed to start”

Can anyone help me?

Thanks

check username setuid **your_user_name** you can check /var/log/syslog for exact problem

While creating the upstart script I cannot start the script. I keep getting “bash: start: command not found”

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
October 19, 2015

@ubq: If you are getting errors saying that start is not a command, it might be an indication that you are trying this on a different distribution than this guide was written for. Are you attempting these procedures on Ubuntu 14.04?

I am trying this on ubuntu 15.10 and got the same error start is not a command. I tried sudo apt-get install upstart after lot of web search but now I get the error start: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refused. Is there a way around?

Hi, I am having an error I can’t find how to solve: 502 Bad Gateway

looking at the log: more /var/log/nginx/error.log

2015/11/04 21:26:40 [crit] 7632#0: *1 connect() to unix:/var/www/apps/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 151.61.114.15, server: 54.193.27.220, request: “GET / HTTP/ 1.1”, upstream: “uwsgi://unix:/var/www/apps/myproject/myproject.sock:” , host: “54.193.27.220”

Is myproject.sock a file created by ningx once it reads the parameters chmod-socket = 660 ?

User in /etc/init/awesome3-gamma.conf is also set correctly.

I tried to create the file myself: touch myproject.sock

but same error.

Also, could you please suggest or point to a resource of how handle two flask sites under the same ningx?

I followed up the tutorial step by step yesterday and was working, today I added my real app and not working, tried to remove the mockup (myproject app) to avoid conflicts pointing at same IP, but stuck in that error. Thank you…

Good tutorial! I like line by line, and also that explains you how to. DigitalOcean is good!

I would add explanations (hyperlinks) to what user and groups ownerships are, if there is misconfiguration or any problem arise from permission, for a newbie as me it is and (has been!) very challenging to debug!

Could you please explain how to handle multiple website with a unique nginx (and multiple sockets I think? )

A configuration could done so to replicate a ‘localhost’ functionality in your laptop: could you please explain how to configure: …/site1/ …/site2/

where each site is an independent flask project,

so to have:

mysite.com/site1/ mysite.com/site2/

?

Follow this tutorial, success finally. Thanks very much!

Still getting the “Welcome to nginx” page when try to open the app with the domain name or IP. And this is after completing the tutorial without any errors. Any idea what I may have omitted or done wrong?

Hi! Do you have answer on your question now? I have the same problem.

I had the same issue. It doesn’t mention in the tutorial but it is necessary to move or delete the default server block config file located at /etc/nginx/sites-enabled/default. Once you remove that file the project config file will be the one used and the app should properly load.

I imagine there is a way to designate the correct config file but I haven;t dug into that yet.

This is a great tutorial; thank you so much!

Do you have any advice for someone who is referencing externally-defined (.bashrc for the moment) environment variables in their flask app? They’re not being pulled in by the upstart script (it works if I manually call uwsgi --ini myproject.ini) and my app won’t run without them

Great tutorial. One question though. Can this setup manage virtual servers like Apache? What if I would like to serve more then one site?

Thanks for the nice guide But I encounter a problem when I just finish creating an App. I just cannot visit the server’s IP address followed by the port number through public network. Have any ideas?

Hey guys, thanks for the tutorial. I have a question. My app works when I run this at the command line uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi…However some pages seem to hang forever when I run with the config file. I get error upstream timeout (110 connection timed out) when reading response header from upstream client …

I searched the web and found increasing proxy_read_timeout 300; and uwsgi_read_timeout 300; This just cause the app to hang for much longer…Like I said everything work as expected on test server. Any ideas what could be the problem?

Justin thnx man…This was an amazingly well written tutorial…I went through everything worked flawlessly dude…

Hi Justin, Hi guys, I’ve got the following error trying to setup a virtual env : OSError: Command /home/louis/myproject/bin/python - pip wheel failed with error code 1

Any clues ? Many thanks,

Louis

Followed the tutorial and got Bad gateway 502 error. Fixed it by changing the permissions to: chmod-socket = 660

HI This is very interesting Tutorials. I followed all the steps that mentioned here. But I cannot use URLs with CURL command But I can access it via web browser I have tried so many time but i couldn’t find a way to solve this can any one help me for this?

Hello @jellingwood , how are you?

I’m trying to follow along this guide, but when I try

sudo start myproject

my VPS returns me this message:

start: Job failed to start

How can I fix this?

I’m running an Ubuntu 14.04 Droplet. I already to all the previous steps. Successfully. And I have tried both Python2 and Python3 Virtual Environments, but the same error…

Cheers,

Cesar Zaneti

Im getting an internal server error, here is what I found in my logs.

flask@dcops-1gb-nyc2-01:~/degrade-monitor$ sudo cat /var/log/upstart/app.log
--- no python application found, check your startup logs for errors ---
[pid: 2314|app: -1|req: -1/2] 162.243.191.74 () {34 vars in 419 bytes} [Thu May 12 23:33:20 2016] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
flask@dcops-1gb-nyc2-01:~/degrade-monitor$ sudo cat /var/log/nginx/error.log
2016/05/12 23:30:21 [crit] 2218#0: *7 connect() to unix:/home/flask/degrade-monitor/app.sock failed (2: No such file or directory) while connecting to upstream, client: 24.146.197.148, server: 107.170.40.187, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/flask/degrade-monitor/app.sock:", host: "107.170.40.187"
Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
May 13, 2016

@Dustinshasho Hey Dustin, it looks like the problem is originating with the Upstart file, but it could also be something in the .ini file.

You can check that your .ini file is working to rule that out. Enter the project directory and making sure your virtual environment is active:

  1. cd ~/myproject
  2. source myprojectenv/bin/activate

Then, pass the .ini file to the uwsgi process:

  1. uwsgi --ini myproject.ini

If the process starts up correctly, the it should end by spawning workers and waiting for connections:

Output
. . . *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 7949) spawned uWSGI worker 1 (pid: 7952, cores: 1) spawned uWSGI worker 2 (pid: 7953, cores: 1) spawned uWSGI worker 3 (pid: 7954, cores: 1) spawned uWSGI worker 4 (pid: 7955, cores: 1) spawned uWSGI worker 5 (pid: 7956, cores: 1)

If you get to this point, your .ini file is likely fine. Otherwise, double-check the .ini file.

If uwsgi can process the .ini file without a problem, the Upstart script itself is probably the issue. The items I’d check are:

  • setuid: This should be set to the user who owns the files/directories. This should be your non-root sudo user that you’ve been using for this process.
  • env PATH: Make sure this is set to the correct /bin directory within your project virtual environment. This is how the Upstart script activates your virtual environment.
  • chdir: This should be the base directory of your project.

If all of those items have the correct values, your Upstart script should work. If you changed some items during the configuration (for instance, the placing your project outside of your user’s home directory), that could also impact the Upstart scripts ability to function correctly (due to permissions and ownership, for instance). If that’s the case, I’d suggest following the guide as-is the first time through and then changing things gradually until you figure out what the hang up is.

Hope that helps!

This is a great tutorial; thank you so much!

Do you have any advice for someone who is referencing externally-defined (.bashrc for the moment) environment variables in their flask app? They’re not being pulled in by the upstart script (it works if I manually call uwsgi --ini myproject.ini) and my app won’t run without them

Great tutorial. One question though. Can this setup manage virtual servers like Apache? What if I would like to serve more then one site?

Thanks for the nice guide But I encounter a problem when I just finish creating an App. I just cannot visit the server’s IP address followed by the port number through public network. Have any ideas?

Hey guys, thanks for the tutorial. I have a question. My app works when I run this at the command line uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi…However some pages seem to hang forever when I run with the config file. I get error upstream timeout (110 connection timed out) when reading response header from upstream client …

I searched the web and found increasing proxy_read_timeout 300; and uwsgi_read_timeout 300; This just cause the app to hang for much longer…Like I said everything work as expected on test server. Any ideas what could be the problem?

Justin thnx man…This was an amazingly well written tutorial…I went through everything worked flawlessly dude…

Hi Justin, Hi guys, I’ve got the following error trying to setup a virtual env : OSError: Command /home/louis/myproject/bin/python - pip wheel failed with error code 1

Any clues ? Many thanks,

Louis

Followed the tutorial and got Bad gateway 502 error. Fixed it by changing the permissions to: chmod-socket = 660

HI This is very interesting Tutorials. I followed all the steps that mentioned here. But I cannot use URLs with CURL command But I can access it via web browser I have tried so many time but i couldn’t find a way to solve this can any one help me for this?

Hello @jellingwood , how are you?

I’m trying to follow along this guide, but when I try

sudo start myproject

my VPS returns me this message:

start: Job failed to start

How can I fix this?

I’m running an Ubuntu 14.04 Droplet. I already to all the previous steps. Successfully. And I have tried both Python2 and Python3 Virtual Environments, but the same error…

Cheers,

Cesar Zaneti

Im getting an internal server error, here is what I found in my logs.

flask@dcops-1gb-nyc2-01:~/degrade-monitor$ sudo cat /var/log/upstart/app.log
--- no python application found, check your startup logs for errors ---
[pid: 2314|app: -1|req: -1/2] 162.243.191.74 () {34 vars in 419 bytes} [Thu May 12 23:33:20 2016] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
flask@dcops-1gb-nyc2-01:~/degrade-monitor$ sudo cat /var/log/nginx/error.log
2016/05/12 23:30:21 [crit] 2218#0: *7 connect() to unix:/home/flask/degrade-monitor/app.sock failed (2: No such file or directory) while connecting to upstream, client: 24.146.197.148, server: 107.170.40.187, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/flask/degrade-monitor/app.sock:", host: "107.170.40.187"
Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
May 13, 2016

@Dustinshasho Hey Dustin, it looks like the problem is originating with the Upstart file, but it could also be something in the .ini file.

You can check that your .ini file is working to rule that out. Enter the project directory and making sure your virtual environment is active:

  1. cd ~/myproject
  2. source myprojectenv/bin/activate

Then, pass the .ini file to the uwsgi process:

  1. uwsgi --ini myproject.ini

If the process starts up correctly, the it should end by spawning workers and waiting for connections:

Output
. . . *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 7949) spawned uWSGI worker 1 (pid: 7952, cores: 1) spawned uWSGI worker 2 (pid: 7953, cores: 1) spawned uWSGI worker 3 (pid: 7954, cores: 1) spawned uWSGI worker 4 (pid: 7955, cores: 1) spawned uWSGI worker 5 (pid: 7956, cores: 1)

If you get to this point, your .ini file is likely fine. Otherwise, double-check the .ini file.

If uwsgi can process the .ini file without a problem, the Upstart script itself is probably the issue. The items I’d check are:

  • setuid: This should be set to the user who owns the files/directories. This should be your non-root sudo user that you’ve been using for this process.
  • env PATH: Make sure this is set to the correct /bin directory within your project virtual environment. This is how the Upstart script activates your virtual environment.
  • chdir: This should be the base directory of your project.

If all of those items have the correct values, your Upstart script should work. If you changed some items during the configuration (for instance, the placing your project outside of your user’s home directory), that could also impact the Upstart scripts ability to function correctly (due to permissions and ownership, for instance). If that’s the case, I’d suggest following the guide as-is the first time through and then changing things gradually until you figure out what the hang up is.

Hope that helps!

Level of my English is bad,so I quote the words of others.(sviltodorov May 25, 2015,thanks) I followed the instructions, however I am now getting a 502 Bad Gateway error when I access my server.

Looking at the nginx error logs the problem is :

2016/05/16 00:15:19 [crit] 21029#21029: *1 connect() to unix:/home/qianshui/myproject/myproject.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: localhost, request: “GET /favicon.ico HTTP/1.1”, upstream: “uwsgi://unix:/home/qianshui/myproject/myproject.sock:”, host: “127.0.0.1”, referrer: “http://127.0.0.1/

I thought the point of doing ‘setgid www-data’ was to be able to access the sock. Is there something that should be added to the upstart script that isn’t included here?

One thing to note, in Ubuntu 14.04, Flask and uwsgi will by default run using the UTF-8 encoding. However, when they are run as a process through the upstart script, they will use the ascii encoding instead, which can cause unexpected problems. In order to run them with UTF-8 through upstart, add the following to the upstart script:

env LANG=en_US.UTF-8

Thanks for this tutorial! I finally have a production site running… I pulled a Flask app from github for this tutorial and I’m am not sure how to keep the wsgi.py and the .sock and .ini files safe on digital ocean and not involve them in my version control… is there a tutorial on setting up this exact configuration with git hooks from a local git repo?

Basically, I have changes to the app on my local machine now, but I am afraid if I push my changes to production it’s going to screw up the server settings … and if I merge, it’s going to screw up my local copy… any advice? I know about .gitignore, but it might be too late to ignore…

This comment has been deleted

    Save and close the file when you are finished.

    You can start the process immediately by typing:

    sudo start myproject


    bash: start: command not found

    i use DEBIAN 8.5

    Justin Ellingwood
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 20, 2016

    @aquafresh: Hey there. This tutorial is written for Ubuntu 14.04. While Debian and Ubuntu share much in common, versioning differences can lead to incompatibilities, as in this case. Ubuntu 14.04 uses the Upstart init system (which includes the start command), while Debian 8 uses the systemd init system (which includes different service management commands). These are not interchangeable, so there are some things that need to be changed in order for that to run correctly.

    I suggest that you use the version of this guide written for Ubuntu 16.04 instead. Ubuntu 16.04 uses systemd, just like Debian 8, so there should be fewer differences between the Debian 8 configuration and the Ubuntu 16.04 configuration.

    Hope that helps!

    its , work :D

    uwsgi --ini myproject.ini

    I’m wondering about logging.

    I want to check my flask log informations when typing “sudo start myproject”.

    Log information means that messages on console when running flask app on foreground.

    @jellingwood so for the “job not found” error, I’m on Ubuntu 16 (but wanted to use an upstart script) and what solved it for me (after trying all your other solutions, of which your troubleshooting comment on the .ini file helped since I also had a file permission issue) was having to modify the .conf to include script and end script:

    script
    
      env PATH=/home/user/myproject/myprojectenv/bin
      chdir /home/user/myproject
      exec uwsgi --ini myproject.ini
    
    end script
    

    and then doing a sudo reboot. Not really sure why this now works (relatively new to server configs), but I hope it can be of help to someone else.

    This comment has been deleted

      sudo start myproject always return start: Job failed to start. Any one please suggest what am I doing wrong?

      Level of my English is bad,so I quote the words of others.(sviltodorov May 25, 2015,thanks) I followed the instructions, however I am now getting a 502 Bad Gateway error when I access my server.

      Looking at the nginx error logs the problem is :

      2016/05/16 00:15:19 [crit] 21029#21029: *1 connect() to unix:/home/qianshui/myproject/myproject.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: localhost, request: “GET /favicon.ico HTTP/1.1”, upstream: “uwsgi://unix:/home/qianshui/myproject/myproject.sock:”, host: “127.0.0.1”, referrer: “http://127.0.0.1/

      I thought the point of doing ‘setgid www-data’ was to be able to access the sock. Is there something that should be added to the upstart script that isn’t included here?

      One thing to note, in Ubuntu 14.04, Flask and uwsgi will by default run using the UTF-8 encoding. However, when they are run as a process through the upstart script, they will use the ascii encoding instead, which can cause unexpected problems. In order to run them with UTF-8 through upstart, add the following to the upstart script:

      env LANG=en_US.UTF-8
      

      Thanks for this tutorial! I finally have a production site running… I pulled a Flask app from github for this tutorial and I’m am not sure how to keep the wsgi.py and the .sock and .ini files safe on digital ocean and not involve them in my version control… is there a tutorial on setting up this exact configuration with git hooks from a local git repo?

      Basically, I have changes to the app on my local machine now, but I am afraid if I push my changes to production it’s going to screw up the server settings … and if I merge, it’s going to screw up my local copy… any advice? I know about .gitignore, but it might be too late to ignore…

      This comment has been deleted

        Save and close the file when you are finished.

        You can start the process immediately by typing:

        sudo start myproject


        bash: start: command not found

        i use DEBIAN 8.5

        its , work :D

        uwsgi --ini myproject.ini

        I’m wondering about logging.

        I want to check my flask log informations when typing “sudo start myproject”.

        Log information means that messages on console when running flask app on foreground.

        @jellingwood so for the “job not found” error, I’m on Ubuntu 16 (but wanted to use an upstart script) and what solved it for me (after trying all your other solutions, of which your troubleshooting comment on the .ini file helped since I also had a file permission issue) was having to modify the .conf to include script and end script:

        script
        
          env PATH=/home/user/myproject/myprojectenv/bin
          chdir /home/user/myproject
          exec uwsgi --ini myproject.ini
        
        end script
        

        and then doing a sudo reboot. Not really sure why this now works (relatively new to server configs), but I hope it can be of help to someone else.

        This comment has been deleted

          sudo start myproject always return start: Job failed to start. Any one please suggest what am I doing wrong?

          …Or you can learn Docker and leave the Nginx / uWSGI to an image like this one: https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/

          And just worry about your Flask app.

          Also, if you later want to use a DB like MySQL or Postgres you can add it very easily with Docker. Without having to learn each system and it’s configurations. And the same with most other stacks (Redis, ElasticSearch, Celery with RabbitMQ, etc). (It’s totally worthwhile to learn Docker).

          protocol variable in your uwsgi server should be uwsgi… otherwise you get this: upstream prematurely closed connection while reading response header from upstream, client

          i.e.

          1. uwsgi --socket 0.0.0.0:8000 --protocol=uwsgi -w wsgi

          The instructions are missing a crucial cd ~/myproject line. Without it, uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi doesn’t work. No variation of the argument to -w seemed to work (e.g. -w myproject:wsgi) from outside the myproject` directory.

          Can you update this for systemd? Thanks.

          Or if you are using Docker (and you should), you can leave all that heavy lifting to an image like https://github.com/tiangolo/uwsgi-nginx-flask-docker , that does it all for you, so you can focus on your app code.

          I really appreciate this tutorial. But for less confusing, I think in the file ~/myproject/wsgi.py these lines are not needed?

          if name == “main”: application.run()

          Thanks

          Section “Create an Upstart script” no more works since Ubuntu 15.10. Use systemd service config instead.

          Here is example:

          [Unit]
          Description=uWSGI server instance configured to serve myproject
          
          [Service]
          Type=simple
          PIDFile=/var/run/myproject.pid
          WorkingDirectory=/home/user/myproject
          
          User=user
          Group=www-data
          
          Environment=PATH=/home/user/myproject/myprojectenv/bin
          
          ExecStart=/home/user/myproject/myprojectenv/bin/uwsgi --ini myproject.ini
          ExecStop=/home/user/myproject/myprojectenv/bin/uwsgi --stop /var/run/myproject.pid
          
          [Install]
          WantedBy=multi-user.target
          

          this tutorial is missing a / in the myproject.conf at the end of bin. As a result, myproject.sock is not created and you get a 502 bad gateway error when you access the site. Probably happened to everyone who copypasted it from this tutorial.

          in the file wsgi.py:

          if __name__ == "__main__":
                  application.run()
          

          the conditional statement is causing a problem with running the command

          uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi
          

          its probably because uwsgi load the wsgi.py as a module externally from another .py file, but not called directly from the wsgi.py file itself(beg my english).

          put the application.run() outsite of the if statement works out for me.

          ps: I know its not the best practice not put the if statement in .py file, please let me know if there is any other work around

          when I am trying this command:

          uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi
          

          getting an error:

          “unable to load configuration from wsgi”

          Change

          uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi
          

          into

          uwsgi --socket 127.0.0.1:8080 --protocol=http --module wsgi --callable app
          

          if you face unable to find "application" callable in file wsgi.py problem.

          I have spent several hours chasing “no python application found”, changing from “module = wsgi” to “wsgi-file = wsgi.py” in *.ini file helped me, I would be happy if someone could explain the difference.

          Very nice tutorial, thank you!

          Would be really cool to extend it into a docker image. Is that something you are willing to do?

          thanks for good tutorial. when I want to start myproject with this command: sudo start myproject

          sudo: start: command not found can anyone help me??

          I have got online server, and I was trying to host a flask application on it, but it did not work, so I followed this tutorial and the Hello There examples here to run the example first but it did not work.

          when I run the myproject.py I got the following output:

          • Serving Flask app “myproject” (lazy loading)
          • Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. Debug mode: off Running on http://0.0.0.0:5000/

          when I try to access my server http://xxx.xxx.xxx.xxx:5000/ it doesn’t give me any response and not working at all.

          what is the exact problem and how to solve it

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.