In this guide, we will be setting up a simple Python application using the Flask micro-framework on Ubuntu 16.04. The bulk of this article will be about how to set up the Gunicorn application server to launch the application and Nginx to act as a front end reverse proxy.
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 the WSGI specification that our application server will use to communicate with our Flask app, 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.
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 some of the Gunicorn components. We’ll install Nginx now as well.
Update your local package index and then install the packages. The specific packages you need will depend on the version of Python you are using for your project.
If you are using Python 2, type:
If, instead, you are using Python 3, type:
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
.
If you are using Python 2, type:
If you are using Python 3, type:
Now, we can make a parent directory for our Flask project. Move into the directory after you create it:
We can create a virtual environment to store our Flask project’s Python requirements by typing:
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:
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$
.
Now that you are in your virtual environment, we can install Flask and Gunicorn and get started on designing our application:
We can use the local instance of pip
to install Flask and Gunicorn. Type the following commands to get these two components:
Note
Regardless of which version of Python you are using, when the virtual environment is activated, you should use the pip
command (not pip3
).
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
:
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:
This basically defines what content to present when the root domain is accessed. Save and close the file when you’re finished.
If you followed the initial server setup guide, you should have a UFW firewall enabled. In order to test our application, we need to allow access to port 5000.
Open up port 5000 by typing:
Now, you can test your Flask app by typing:
Visit your server’s domain name or IP address followed by :5000
in your web browser:
http://server_domain_or_IP:5000
You should see something like this:
When you are finished, hit CTRL-C in your terminal window a few times to stop the Flask development server.
Next, we’ll create a file that will serve as the entry point for our application. This will tell our Gunicorn server how to interact with the application.
We will call the file wsgi.py
:
The file is incredibly simple, we can simply import the Flask instance from our application and then run it:
Save and close the file when you are finished.
Before moving on, we should check that Gunicorn can correctly.
We can do this by simply passing it the name of our entry point. This is constructed by the name of the module (minus the .py
extension, as usual) plus the name of the callable within the application. In our case, this would be wsgi:app
.
We’ll also specify the interface and port to bind to so that it will be started on a publicly available interface:
Visit your server’s domain name or IP address with :5000 appended to the end in your web browser again:
http://server_domain_or_IP:5000
You should see your application’s output again:
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:
Any Python commands will now use the system’s Python environment again.
The next piece we need to take care of is the systemd service unit file. Creating a systemd unit file will allow Ubuntu’s init system to automatically start Gunicorn and serve our Flask application whenever the server boots.
Create a unit file ending in .service within the /etc/systemd/system directory to begin:
Inside, we’ll start with the [Unit]
section, which is used to specify metadata and dependencies. We’ll put a description of our service here and tell the init system to only start this after the networking target has been reached:
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
Next, we’ll open up the [Service]
section. We’ll specify the user and group that we want the process to run under. We will give our regular user account ownership of the process since it owns all of the relevant files. We’ll give group ownership to the www-data
group so that Nginx can communicate easily with the Gunicorn processes.
We’ll then map out the working directory and set the PATH
environmental variable so that the init system knows where our the executables for the process are located (within our virtual environment). We’ll then specify the commanded to start the service. Systemd requires that we give the full path to the Gunicorn executable, which is installed within our virtual environment.
We will tell it to start 3 worker processes (adjust this as necessary). We will also tell it to create and bind to a Unix socket file within our project directory called myproject.sock
. We’ll set a umask value of 007
so that the socket file is created giving access to the owner and group, while restricting other access. Finally, we need to pass in the WSGI entry point file name and the Python callable within:
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
Environment="PATH=/home/sammy/myproject/myprojectenv/bin"
ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
Finally, we’ll add an [Install] section. This will tell systemd what to link this service to if we enable it to start at boot. We want this service to start when the regular multi-user system is up and running:
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
Environment="PATH=/home/sammy/myproject/myprojectenv/bin"
ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target
With that, our systemd service file is complete. Save and close it now.
We can now start the Gunicorn service we created and enable it so that it starts at boot:
Our Gunicorn 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 by making some small additions to its configuration file.
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:
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 proxy_params
file that specifies some general proxying parameters that need to be set. We’ll then pass the requests to the socket we defined using the proxy_pass
directive:
server {
listen 80;
server_name server_domain_or_IP;
location / {
include proxy_params;
proxy_pass http://unix:/home/sammy/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:
With the file in that directory, we can test for syntax errors by typing:
If this returns without indicating any issues, we can restart the Nginx process to read the our new config:
The last thing we need to do is adjust our firewall again. We no longer need access through port 5000, so we can remove that rule. We can then allow access to the Nginx server:
You should now be able to go to your server’s domain name or IP address in your web browser:
http://server_domain_or_IP
You should see your application’s output:
Note
After configuring Nginx, the next step should be securing traffic to the server using SSL/TLS. This is important because without it, all information, including passwords are sent over the network in plain text.
The easiest way get an SSL certificate to secure your traffic is using Let’s Encrypt. Follow this guide to set up Let’s Encrypt with Nginx on Ubuntu 16.04.
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 Gunicorn app server to provide this function. Afterwards, we created a systemd unit file 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.
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!
Thanks, great tutorial!
Although I am having a problem and I hope you could help. .service
configuration file in Nginx’s
But if I connect to the address I get a “502 Bad Gateway” response…
@ixtora: Hello. From a quick glance, it looks like the socket files in your two configuration files don’t match. In the systemd file, you are telling Gunicorn to create a
myproject.sock
file. However, in your Nginx configuration, it looks like you are trying to connect to aflasktest.sock
file. Try changing those to match and see if that works.Hello. Thanks for the answer. This code I copied to the lesson, consequently made a mistake. In systemd everything correctly. Problem solved. I found the problem after viewing the log service.
I have created the service and now it is running. Can I access my app at this point without proxying request through nginx ?
This comment has been deleted
Thanks, great tutorial! I follow this and it worked, just 1 thing to note. In my up to date ubuntu16.04(June 24) , In Configuring Nginx to Proxy Requests section, in /etc/nginx/sites-enabled folder ,there is a “default” file. fisrt time I enter http://server_domain_or_IP in browser ,get nginx welcome page. We should remove this file to get our ‘hello there’ page.
Hi, My name is sender, and a trying to finish this instalation, but I dont know whats is the problem. 502, bad gateway. when simulation occurs, it appears the “hello there”, but when I try to activate the second part appears this error, I am sending my settings…
\etc\nginx/nginx.conf
server { listen 80; server_name 10.0.0.50;
/etc/systemd/system/meuprojeto.service
[Unit] Description=uwsgi instance to serve meuprojeto2 After=network.target
[Service] User=sender Group=nginx WorkingDirectory=/home/sender/meuprojeto2 Environment=“PATH=/home/sender/meuprojeto2/meuprojeto2env/bin” ExecStart=/home/sender/meuprojeto2/meuprojeto2env/bin/uwsgi --ini meuprojeto2.ini
[Install] WantedBy=multi-user.target
To clarify in case anyone else has this problem:
In the file: /etc/systemd/system/myproject.service
This line: ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
On our system it turns out gunicorn is not located here: /home/sammy/myproject/myprojectenv/bin/gunicorn
rather it is located here: /usr/local/bin/gunicorn
It took our apprentice several days to figure this one out. You might want to clarify this alternative.
@rithythul: Hello! If your
gunicorn
process is located at/usr/local/bin/gunicorn
, it might be an indication that you did not have your virtual environment enabled when you installed it. To install it to the virtual environment, as this guide demonstrates, make sure you activate your virtual environment first by typing:Afterwards, the Gunicorn installation command should install to the virtual environment:
Hopefully that helps.
I followed the steps exactly and in the end I got the “Hello There!” message to show up at my server’s IP address. However, when I rebooted my server and ssh’ed in, I could not get it to work. After that I could no longer connect and get the “Hello There!” message to appear. I get the same message that the IP address refused to connect.
I followed the example but I get error 502. When I checked the error logs at /var/log/nginx/error.log. It says no directory or file /home/dapo/myproject/myproject.sock
I fix it, since the myproject.sock has to be created by gunicorn, all I did is to restart gunicorn like “sudo systemctl restart myproject” then I did “sudo systemctl restart nginx” and it works
Thank you!!
I am still getting the 502 Gateway error. I have checked the log of nginx and it says there is no "/home/root/myproject/myproject.sock file. Like the last the last person to post a question I have double checked my setup files. Here is the error.log file:
2016/08/11 12:10:41 [emerg] 13854#13854: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:10:41 [emerg] 13854#13854: still could not bind() 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2016/08/11 12:29:50 [emerg] 14125#14125: still could not bind() 2016/08/11 13:43:46 [emerg] 14499#14499: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:43:46 [emerg] 14499#14499: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:43:46 [emerg] 14499#14499: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:43:46 [emerg] 14499#14499: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:43:46 [emerg] 14499#14499: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:43:46 [emerg] 14499#14499: still could not bind() 2016/08/11 13:45:21 [emerg] 14535#14535: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:45:21 [emerg] 14535#14535: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:45:21 [emerg] 14535#14535: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:45:21 [emerg] 14535#14535: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:45:21 [emerg] 14535#14535: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:45:21 [emerg] 14535#14535: still could not bind() 2016/08/11 13:48:55 [emerg] 14644#14644: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:48:55 [emerg] 14644#14644: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:48:55 [emerg] 14644#14644: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:48:55 [emerg] 14644#14644: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:48:55 [emerg] 14644#14644: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2016/08/11 13:48:55 [emerg] 14644#14644: still could not bind() 2016/08/11 13:51:55 [crit] 14722#14722: *1 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET / HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/”, host: “188.166.226.199” 2016/08/11 13:51:55 [crit] 14722#14722: *3 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET /favicon.ico HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/favicon.ico”, host: “188.166.226.199”, referrer: “http://188.166.226.199/” 2016/08/11 14:01:44 [crit] 14870#14870: *1 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET / HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/”, host: “188.166.226.199” 2016/08/11 14:09:54 [crit] 14870#14870: *3 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET / HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/”, host: “188.166.226.199” 2016/08/11 14:10:16 [crit] 14870#14870: *5 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET / HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/”, host: “188.166.226.199” 2016/08/11 14:12:34 [crit] 14955#14955: *1 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET / HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/”, host: “188.166.226.199” 2016/08/11 14:12:34 [crit] 14955#14955: *3 connect() to unix:/home/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 61.93.120.56, server: 188.166.226.199, request: “GET /favicon.ico HTTP/1.1”, upstream: “http://unix:/home/root/myproject/myproject.sock:/favicon.ico”, host: “188.166.226.199”, referrer: “http://188.166.226.199/” root@ianwj:~# sudo systemctl restart myproject root@ianwj:~# sudo systemctl restart nginx root@ianwj:~# cd myproject root@ianwj:~/myproject# ls myproject.py myproject.pyc myprojectenv wsgi.py wsgi.pyc root@ianwj:~/myproject# cd etc/nginx/sites-available -bash: cd: etc/nginx/sites-available: No such file or directory
Sorry for the longwinded post…
@ian796072667fc9: Hello. There seem to be a few things going on here.
First, as it states in the prerequisites, you appear to be using the
root
user. This guide assumes that you are using a non-root user. Using root is not only insecure, it will cause problems when following this guide.Second, it does not appear that you entered the project directory correctly in the Nginx configuration file. Since you are using the
root
user, the/home/username/...
prefix does not fit anymore. Theroot
user’s home directory is/root/...
, so you should use that in yourproxy_pass
definition.If your
.sock
file does not exist, that indicates that the the project’ssystemd
step (the one callinggunicorn
is having issues. You can check the logs produced when trying to start your project by typing:That should give you some indication as to what is going on with the project.
Hope that helps.
Thx for the information. I rebuilt the whole tutorial as “ian@ianwj” user. (Got out of “root”) Had to do as the last person posted: “I fix it, since the myproject.sock has to be created by gunicorn, all I did is to restart gunicorn like “sudo systemctl restart myproject” then I did “sudo systemctl restart nginx” and it works” Now working… Thx.
One last noob question: I changed the “myproject.py” to replace Hello There! with another message. Restarted myproject and nginx but still get Hello There! when browsing to my IP address.
" “sudo systemctl restart myproject” " – that should do it.
I am very frustrated by the fact that at times, I get an error 502 bad gateway error or an error 500 internal server error. This will go away when I run the sudo systemctl restart myproject and after some days it comes back and this is really affecting my business.
When I check my error logs I often get this
2016/10/20 23:37:18 [crit] 12366#12366: *47260 connect() to unix:/home/myusername/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 78.206.179.140, server: 000.111.222.333, request: “GET /goods HTTP/1.1”, upstream: “http://unix:/home/myusername/myproject/myproject.sock:/goods”, host: “000.111.222.333”, referrer: “http://000.111.222.333/goods”
Can it just work well once and for all or does it just kills it connections.
same is happening to me right now. By looking at
sudo journalctl -u myproject
I did find some errors though… not sure if that’s relatedI loved this tutorial. However, could you elaborate on what exactly is happening with the wsgi.py file and how my the app is speaking with gunicorn and nginx? Also, how can we clean up our working directory to store the wsgi.py and myproject.sock file to another folder so its out of the way? I would assume with git we would gitignore the sock file and wsgi.py file?
Hey guys,
I’m pretty new to this but having some issues and I’ve done all that I think I could to troubleshoot. I’m not getting any major issues in the error.log for nginx or the gunicorn log(journalctl).
I have this for my stats.service file
[Unit] Description=Gunicorn instance to serve stats After=network.target
[Service] User=mainuser Group=www-data WorkingDirectory=/home/mainuser/stats Environment=“PATH=/home/mainuser/stats/stats/bin” ExecStart=/home/mainuser/stats/stats/bin/gunicorn --workers 3 --bind unix:stats.sock -m 007 wsgi:app
[Install] WantedBy=multi-user.target
and this for my nginx file
server { listen 80; server_name 192.241.204.247; allow 192.241.204.247;
}
As I said before no errors show up in the logs but when I go to the IP (192.241.204.247) nothing shows, just the ‘this site can’t be reached - 192.241.204.247 refused to connect.’ Thought it might be the firewall but I have that available to Nginx. When I did the test in the virtual env with port 5000 at the end that worked. But when I’m outside of the venv and trying to see something it’s not working.
To Action From
OpenSSH ALLOW Anywhere
Apache Full ALLOW Anywhere
Nginx Full ALLOW Anywhere
5000 ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Apache Full (v6) ALLOW Anywhere (v6)
Nginx Full (v6) ALLOW Anywhere (v6)
5000 (v6) ALLOW Anywhere (v6)
So does anyone know the correct way to open a port in UFW so I can continue to use pip to install things? I tried:
But I didn’t have any luck with that. Other thoughts?
When i finish all settings, i show “Welcome to nginx!” page, not “Hello There” page. Please help ???
@ArdaMavi Sorry to hear you had an issue. The part that should be preventing the default Nginx page from being served is setting the
server_name
directive in the new file to the domain name or IP address used for the request.By default, the
/etc/nginx/sites-enabled/default
file in the Nginx package in Ubuntu’s repository will have theserver_name
set to_
, which is just an invalid hostname. Since that server block is defined as thedefault_server
for port 80 (you can see that in thelisten
declaration), it means that this server block should only be used if no others match the request better:I’m not sure why you’re experiencing this issue, but I would check that the
server_name
in/etc/nginx/sites-enabled/default
is still set to_
and theserver_name
in the new file is set to your server’s IP address or domain name.If you set the
server_name
in the new file to the server’s valid IP address or domain name, this should be a more exact match than the invalid_
match and should be selected to serve the request. The way you request your page has to be one of the things you add to theserver_name
for it to match. You can find more about how Nginx chooses the server block to server requests here.It is possible to provide more than one value, so I suggest adding any method you may be using to contact the server, like this:
Remember to restart Nginx after making changes.
Hopefully this helps a bit. Like I said, I’m unsure of why you’re seeing this behavior, but this is my first best guess.
I do all settings now and i get “bad gateway” ?
Ok! Thank you i do. I create user and try again all settings. Thats it. But Why ? :D :D
So I got the tutorial site working, but now I would like to use my own flask app (which uses modules) and serve html,css and js files. I tried to create static and template folders to the myproject folder, but it doesn’t work. I also tried to install all the modules my app requires. I just keep getting “502 bad gateway”
I already added this to some nginx file
I’m really bad with this kind of server setup things. I picked flask because it was easy to get working on localhost but now it seems very complicated. But yeah I would like to get my flask app working.
I was having 502 bad gateway errors as well, I eventually fixed it by changing the
/etc/systemd/system/myproject.service
file.it’s related to the
myprojectenv
line, which should actually just bemyproject
I’m in the process of migrating a Flask application of mine to Digital Ocean and found this tutorial to be very helpful. However, though things worked perfectly fine when I tested the app in the earlier steps, once I made the systemd unit file and tried to test it I got bad gateway errors. I ran
sudo journalctl -u myproject
and saw that the errors were being thrown when my project was reading from a couple json/txt files I have in my project. The error being thrown was UnicodeDecodeError: ‘ascii’ code cannot decode byte …. After searching online a bit, I found that by addingLC_ALL="en_US.UTF-8"
to /etc/environment I was able to access my project successfully.Hope this helps someone else.
Thanks for this helpful tutorial.
I am trying a variation and struggling if you have any input.
I am using Anaconda environments, and so in my systemd unit file the [Service] part looks different. With my conda env named ‘flask’, I tried:
No error messages (or messages at all) when I run:
But when I run:
I get:
I tried it out again using
And saw the same error output from
sudo systemctl enable mysite
(but reassuringly could see the website start/stop with systemctl start/stop).Also, running this works fine (from the mysite directory, with my flask conda env activated):
Any ideas what’s wrong? Where-to-look-next guidance?
I am having a hard time finding anything about systemd error logs (if they exist) or how to troubleshoot systemd unit files.
Thanks
I am logged in as root and have set permissions for root:www-data to rw for solytics_api.sock.
I am seeing this error repeatedly however, [crit] 3702#3702: *1 connect() to unix:/root/Solytics/SolyticsScript/SolyticsAPI/solytics_api.sock failed (13: Permission denied) while connecting to upstream,
under /etc/systemd/system/solytics_api.service I have set user: root group: www-data
I have also run chown -R root:www-data solytics_api.sock from the working directory.
Any advice?
This is a nice, thorough tutorial.
A couple of things that I found:
I followed the instructions and got everything working on my IP address however when I visit mydomain.com I get a “Welcome to nginx!”
Not a clue what is going on
I would guess it’s that you have two configurations in
/etc/nginx/sites-enabled/
, including the one you want and one calleddefault
. I would remove thedefault
one and change the server line of your nginx configuration file so it reads.Thanks, I already solved it.
It was nothing to do with the code, I had a problem with FileZilla and it wasn’t updating my file edits.
Before I had:
server_name server_IP
The edit that work:
server_name server_IP server_domain www.server_domain
Hi, I have followed this tutorial with only difference - I am using miniconda3 with conda virtualenv. I am getting 502 Bad Gateway. Name of my flask app is hntrends. My files look like this:
/etc/systemd/system/hntrends.service
/etc/nginx/sites-available/hntrends
Output of sudo journalctl -u hntrends is:
Could you please help me? Is this related to my configuration of virtualenv using conda?
@xbabinec Sorry to hear that you’re having trouble. It looks like it doesn’t like your
Environment
declaration in your/etc/systemd/system/hntrends.service
file:This could be because of a few different reasons.
First, check that the directory exists exactly as written (copy and paste the path from your file directly) by testing the location on the command line:
Your output should looks something like this if the directory exists.
If that check passes, check the permissions on the directory and all of its parents with the
namei
command. You must pass the entire absolute path, not a relative path, for this to check the whole path:In the output, check that the other group in the permissions (the last three characters in the first column) allow both read (
r
) and execute (x
) permissions on each of the directories leading up to thebin
directory. If these permissions aren’t present, the directory might be inaccessible when the service is started:Those are the first two things I would look at. Hopefully that points you in the right direction.
I have issue i manage to make all the configuration and now experiencing a bad request.
.service
.nginx
This comment has been deleted
@rmuhire Hey there. It looks like you’ve been using the
root
user to complete the steps in this guide. The steps listed here are written assuming that you are logged in as a non-root user withsudo
privileges. The reason this is important is that theroot
user’s home directory, located at/root
has restrictions that are not present in the/home/<username>
home directories for normal users. As the error you posted indicates, Nginx is unable to connect to the socket file because the parent directory is locked down.To fix this, your best option is to either start over from the beginning using a
sudo
user, or to create asudo
user now and then transfer your project’s files to the correct directory and ownership with the following steps (this assumes your username issammy
, so switch that to your user’s real name):You’ll then need to adjust the
/etc/systemd/system/myproject.service
file and the/etc/nginx/sites-available/myproject
file to point to the new locations for your files.Afterwards, restart the services by typing:
That should hopefully get your system into a better state.
I’d suggest adding the following line after
ExecStart
in/etc/systemd/system/myproject.service
:This way you can run
systemctl reload myproject
to reload your app’s code files (for example if you’ve edited them) without actually restarting gunicorn.Hi, you write a great tutorial about it. May I translate it into Chinese and repost it with source link to my blog?
@akakanch Hey there. All content on the DigitalOcean Community site is shared under an Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Licence, so yes!
The terms specify that you’re free to take it and modify it provided that it’s not for commercial purposes, you attribute the original work, and that you share your version under the same license. You can learn more by checking out the official terms of the license here. I hope that helps!
Thank you
Regarding this step, is the socket file that’s created supposed to be created permanently or temporarily? Mine disappears very soon after, and I think that produces the nginx error I receive (in the nginx logs):
connect() to unix:/home/.../.../application.sock failed (2: No such file or directory) while connecting to upstream
)There are various problems with this guide, you will not be able to follow it as is on Ubuntu 16.04. The main issues to take notice:
The folders
sites-available
andsites-enabled
are not created when nginx is installed; they are not part of a vanilla nginx install. They must be created by user, and included in thenginx.conf
file. Details here: https://stackoverflow.com/a/17415606/2066215Verifying the nginx configuration as provided here results in an error:
That is because the
proxy_params
file is neither part of the vanilla nginx install. You can either create it yourself or add its contents to the/etc/nginx/sites-available/myproject
file. Details here: https://stackoverflow.com/a/42591098/2066215Cheers.
Followed the tutorial, everything is working fine until Configuring nginx to proxy requests. At the end I get a 502 bad getaway error. I checked the nginx error log and I get the following:
When I try to run manually on my virtual env
I get the following error:
And when I run sudo systemctl status sample_app.service i get the following:
Anyone faced similar issues? Any idea on how to solve it?
@bernatsopena Sorry to hear you’re having trouble. From the output you provided for
sudo systemctl status sample_app.service
, it looks like you may have a typo in your file:Try checking your
/etc/systemd/system/sample_app.service
file again to see if there’s anything you need to change. Hope that sets you in the right direction! Good luck!Thanks, great tutorial. Works perfectly.
For some people who get a 502 Bad Gateway, perhaps you forgot to edit this particular line of code that slides off the code box:
Go back and make sure you change “unix:myproject.sock” to "units:[WHATEVER YOUR PROJECT’S NAMNE IS, PUT IT HERE].sock.
After securing traffic using SSL/TTS I can not connect application like this anymore.
http://server_domain_or_IP
I get 404 error. Is there a way to fix this.
Hi, this guide works perfectly for me besides routes that aren’t at /. I have
@app.route(‘/’) def index(): return render_template(‘index.html’)
and it works perfectly, but I also have
@app.route(‘/setup’) def setup(): return render_template(‘setup.html’)
but that just returns a 404 Not Found by nginx.
Hi, I have followed this tutorial with only difference - I am using miniconda3 with conda virtualenv. I am getting 502 Bad Gateway. Name of my flask app is hntrends. My files look like this:
/etc/systemd/system/hntrends.service
/etc/nginx/sites-available/hntrends
Output of sudo journalctl -u hntrends is:
Could you please help me? Is this related to my configuration of virtualenv using conda?
@xbabinec Sorry to hear that you’re having trouble. It looks like it doesn’t like your
Environment
declaration in your/etc/systemd/system/hntrends.service
file:This could be because of a few different reasons.
First, check that the directory exists exactly as written (copy and paste the path from your file directly) by testing the location on the command line:
Your output should looks something like this if the directory exists.
If that check passes, check the permissions on the directory and all of its parents with the
namei
command. You must pass the entire absolute path, not a relative path, for this to check the whole path:In the output, check that the other group in the permissions (the last three characters in the first column) allow both read (
r
) and execute (x
) permissions on each of the directories leading up to thebin
directory. If these permissions aren’t present, the directory might be inaccessible when the service is started:Those are the first two things I would look at. Hopefully that points you in the right direction.
I have issue i manage to make all the configuration and now experiencing a bad request.
.service
.nginx
This comment has been deleted
@rmuhire Hey there. It looks like you’ve been using the
root
user to complete the steps in this guide. The steps listed here are written assuming that you are logged in as a non-root user withsudo
privileges. The reason this is important is that theroot
user’s home directory, located at/root
has restrictions that are not present in the/home/<username>
home directories for normal users. As the error you posted indicates, Nginx is unable to connect to the socket file because the parent directory is locked down.To fix this, your best option is to either start over from the beginning using a
sudo
user, or to create asudo
user now and then transfer your project’s files to the correct directory and ownership with the following steps (this assumes your username issammy
, so switch that to your user’s real name):You’ll then need to adjust the
/etc/systemd/system/myproject.service
file and the/etc/nginx/sites-available/myproject
file to point to the new locations for your files.Afterwards, restart the services by typing:
That should hopefully get your system into a better state.
I’d suggest adding the following line after
ExecStart
in/etc/systemd/system/myproject.service
:This way you can run
systemctl reload myproject
to reload your app’s code files (for example if you’ve edited them) without actually restarting gunicorn.Hi, you write a great tutorial about it. May I translate it into Chinese and repost it with source link to my blog?
@akakanch Hey there. All content on the DigitalOcean Community site is shared under an Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Licence, so yes!
The terms specify that you’re free to take it and modify it provided that it’s not for commercial purposes, you attribute the original work, and that you share your version under the same license. You can learn more by checking out the official terms of the license here. I hope that helps!
Regarding this step, is the socket file that’s created supposed to be created permanently or temporarily? Mine disappears very soon after, and I think that produces the nginx error I receive (in the nginx logs):
connect() to unix:/home/.../.../application.sock failed (2: No such file or directory) while connecting to upstream
)There are various problems with this guide, you will not be able to follow it as is on Ubuntu 16.04. The main issues to take notice:
The folders
sites-available
andsites-enabled
are not created when nginx is installed; they are not part of a vanilla nginx install. They must be created by user, and included in thenginx.conf
file. Details here: https://stackoverflow.com/a/17415606/2066215Verifying the nginx configuration as provided here results in an error:
That is because the
proxy_params
file is neither part of the vanilla nginx install. You can either create it yourself or add its contents to the/etc/nginx/sites-available/myproject
file. Details here: https://stackoverflow.com/a/42591098/2066215Cheers.
Followed the tutorial, everything is working fine until Configuring nginx to proxy requests. At the end I get a 502 bad getaway error. I checked the nginx error log and I get the following:
When I try to run manually on my virtual env
I get the following error:
And when I run sudo systemctl status sample_app.service i get the following:
Anyone faced similar issues? Any idea on how to solve it?
@bernatsopena Sorry to hear you’re having trouble. From the output you provided for
sudo systemctl status sample_app.service
, it looks like you may have a typo in your file:Try checking your
/etc/systemd/system/sample_app.service
file again to see if there’s anything you need to change. Hope that sets you in the right direction! Good luck!Thanks, great tutorial. Works perfectly.
For some people who get a 502 Bad Gateway, perhaps you forgot to edit this particular line of code that slides off the code box:
Go back and make sure you change “unix:myproject.sock” to "units:[WHATEVER YOUR PROJECT’S NAMNE IS, PUT IT HERE].sock.
After securing traffic using SSL/TTS I can not connect application like this anymore.
http://server_domain_or_IP
I get 404 error. Is there a way to fix this.
Hi, this guide works perfectly for me besides routes that aren’t at /. I have
@app.route(‘/’) def index(): return render_template(‘index.html’)
and it works perfectly, but I also have
@app.route(‘/setup’) def setup(): return render_template(‘setup.html’)
but that just returns a 404 Not Found by nginx.
Hi, this guide works perfectly for me besides routes that aren’t at /.
I have:
@app.route(‘/’) def index(): return render_template(‘index.html’)
@app.route(‘/setup’) def setup(): return render_template(‘setup.html’)
in my code.
Going to website.com works, but going to website.com/setup returns a 404 by nginx.
How do I fix this?
Thanks, This is a great tutorial.
Everything is working fine for me. But the only issue I have is when I try to access the API on https. I have installed an SSL certificate with let’s encrypt but now can’t access the API. It’s timing out every time I try to access the API.
Very Nice And Detailed Tutorial, But This Tutorial misses one crucial thing which made me scratch my head for hours. The Ubuntu Version of Nginx Ships with a "default " site which is pre-enabled. Unless You Delete or Rename this File, You won’t be able to access your Flask App using Gunicorn. Try to rename the default file located in /etc/nginx/sites-available/ to something like default.txt. I recommend not deleting the file since it helps you explain what to do in your next .conf file. After that restart nginx by Typing “sudo systemctl restart nginx” .
Thanks…that’s a good idea to backup the default config instead of deleting it.
How does one use the socket method to serve multiple Flask apps? I’ve been trying to apply the thinking from https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04, but haven’t had any luck getting it to work with Flask, gunicorn, and systemd per the methods in this article. I haven’t found any solid tutorials on using flask, gunicorn, nginx and systemd. The few tutorials I’ve found use supervisor or and specify the port in the nginx config file for the site and don’t use the socket method. I had followed Miguel’s Flask Mega Tutorial but couldn’t get the supervisor to work, but was able to get the microblog to work with the systemd method described in this tutorials. I’m a noob on Python development and since I had followed Miguel’s Flask Mega Tutorial, I’m most comfortable sticking with the python, gunicorn, nginx setup this if possible.
Thanks, Rebecca
what to give in server_name server_domain_or_IP if I haven’t yet bought a domain and just want to test on my local machine ?
Great tutorial. Was able to serve my application on my droplet. Just for others, if you are serving the app, check if app’s directory owner is you(sammy), not the root. I was getting no error, except “gunicorn instance is closed as an info”.
ls -l
for knowing the owner of the folder, and then change owner to you instead of root - refer chown command.Hello.
I am deploying my flask app with PostgreSQL as a database backend and SQLAlchemy as an ORM. Everything was ok (database was created and app was running under gunicorn) until the systemd/nginx part.
Nginx is working correctly, displaying me an InternalServerError, something is wrong on the gunicorn side. From logs I see that
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: password authentication failed for user "myuser"
is raised, but I don’t understand why?