# Python Flask Tutorial: Deploying Your Application (Option #1) - Deploy to a Linux Server

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=goToXTC96Co
- **Дата:** 20.12.2018
- **Длительность:** 1:15:00
- **Просмотры:** 362,236

## Описание

In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.

If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up: 
https://linode.com/coreyschafer

We will be covering the entire deployment of a Flask application. This includes spinning up a new Linux Server and tightening its security with SSH keys and firewalls. Then we will install Nginx and Gunicorn so that we can get our Flask App running. Let's get started...

To skip the server setup, jump to 26:48

How to Run Linux/Bash on Windows: https://youtu.be/xzgwDbe7foQ

SSH Key-Based Authentication Tutorial: https://youtu.be/vpk_1gldOAE

SSH Keys on Windows: https://www.linode.com/docs/security/authentication/use-public-key-authentication-with-ssh/#windows

NGINX config used in this video:
https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/snippets/nginx.conf

Supervisor config used in this video:
https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/snippets/supervisor.conf


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1

✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/

#Python #Flask

## Содержание

### [0:00](https://www.youtube.com/watch?v=goToXTC96Co) Intro

hey there how's it going everybody in this video we're going to be continuing the flask series and learning how to deploy our flask application to a web server so that anyone with internet access can use it within a browser so far we've created this application with some good functionality but the site still only lives on our local machine right now this is just running in my browser on my local machine but no one else can access this so the point of building these sites is to deploy them so that they're accessible over the Internet now I'm not gonna lie to you deploying can be a bit tricky it can be overwhelming because there are a lot of different ways to deploy an application and it's hard to know exactly what's best for your specific application so we're gonna look at several deployment options in this series so we're gonna look at how to deploy to our own linux server Heroku and possibly some others so in this video we're going to be learning how to deploy our application to our own linux server using nginx and g unicorn now if you watched my django series then i deployed the django application using apache and mod whiskey but the reason I used in that video is because it's recommended on Django site but with flask I think it'll be best for us to use engine X and G unicorn so when you deploy to a Linux server you're most likely going to be deploying to a virtual machine that is hosted by a company so that's going to be a company like lenôtre or digitalocean or AWS now I personally use 'la node for my own web applications so that's what we'll be using in this video and the node was actually kind enough to sponsor this video as well and has provided me with a link where you all can get 20 dollars of free credit towards an account so if you want to follow along with this video then I'll leave that link in the description section below where you can sign up for an account and get enough credit to follow along I've been using their services for my own personal website for years so I was really happy when they contacted me about sponsoring a video so with that said let's go ahead and get started ok so like I said we're going to be deploying it to a Linux server this method of deployment actually takes the most effort to set up but is also the most flexible in terms of what control you're going to have over your application and web server so in future videos we'll look at deployment options that offer some free tiers but they usually only offer basic services so for example if you want to use your own domain name like you know my flask blog. com or something like that then you'll have to upgrade to a paid service on those free options in order to set that up and even then you won't have the freedom and possibilities that you get when you have your own virtual private server so the way that we're going to do it in this video will give you a lot of freedom and room for your application to grow but it's not as simple as some of the other methods so there definitely are some trade-offs there so like I said I'm going to be using lenôtre ploy this application to a linux server so that's my personal preference but you can do the same deployment with any linux server that you can access via SSH now I already have an account with OneNote so I'm going to pull that up here in the browser so let me reload this page to make sure I'm still logged in now I'm going to show you how to create and set up a Linux server from scratch because that's what a lot of you have requested but if you already have a server ready to go and want to skip directly do the flat specific deployment then I'll put a timestamp in the description section below or you can jump to that part so if you create an account with a node then you should be able to access a page like this that I have in front of me here now this is their new cloud manager at cloud le node calm there's also a lenôtre at manage node comm but I think that's older and they are suggesting that people switch over to this so this page gives me access to all of my currently node servers so you can see here that I already have one created for my personal website called core EMS server but we're going to create a new one from scratch to deploy our flask application so let's go ahead and do that now so to do this I can just come up here to create so I'm going to click on create and we're the node so the node is their names for their linux server you can see here it says high-performance sss state linux servers for all your infrastructure needs so i'm going to click on that and now we choose our image or our operating system so i'm going to use a boon to here a boon 218 and now we need to choose a region i'm just going to choose dallas texas but you can see that they also have regions and europe and asia as well so you probably want to choose a server that is going to be close to your audience so I'm going to choose Dallas Texas because it's a nice midpoint in the United States ok so now we can choose our Linode plan so these are the standard plans here you can see some of the computer specs and the prices so this is $10 a month $20 a month one CPU 50 gigs of storage 2 gigs of RAM they also have something here called an anode now this is a low performance machine but it's also a cheaper option so you can see this is one CPU 25 gigs of storage and one gig of ram but since our application is pretty simple and we're just testing this out and trying to deploy it I'm just going to choose this cheapest option because it's not gonna take a lot of resources okay so now let's choose a label so I'm just going to call this flask - server and I'm gonna skip and not add any tags here and now we're gonna add a root password so I'm of just this is a test with some capitalization in there but you're gonna want a stronger root password obviously for your own server now you're definitely going to want to remember this password as well because this is what you're going to use to first log in to the system now you can see that they have some optional add-ons here such as backups and private IP I would probably recommend getting a backup if this is going to be your production server so that you don't have to worry about it but I'm not gonna do it for this since we are just testing this deployment so I'm just going to come over here and click on create and now it's going to create this server so we can see here that it's now provisioning the server and after it provisions it then it will boot the server up so I'm going to skip forward to where this is complete so I will resume once this is finished ok so our new server has finished booting up and that only took a couple of minutes so now we can see it here in our list of Leno's if we go to dashboard then we can also see the lenôtre listed there as well so now all we need to do is click on this server and then go to the networking tab and once you're in the networking tab you can see here that we have this SSH command so this SSH command is how we're going to first access our machine now you're going to want to write down this IP address because we're going to be using that a lot throughout this video so I'm gonna write mine down right now it is for 5. 3 3. 1 to 3 dot 2 1 4 so now I'm going to copy this SSH command and now I'm going to paste this into my command line to login to my server now if you're in a Windows machine then you might not have access to the SSH command there are other tools that you can use that allow you to SSH into a server so one of the more popular tools is called putty but personally what I recommend if you're on a newer version of Windows is to simply install the Linux bash shell on Windows and you'll be able to as I say it's through that now I'm not going to show that process in this video but I do have a separate video detailing that whole process and I'll put a link to that in the description section below and also putty here I also have this opened up here in the browser if you do want to download putty that is at putty org so you can find that there and there will be instructions for how to use SSH with putty on that site in their documentation but if you are using Linux bash shell then it will allow you to more easily follow along with all of the commands in this video ok so if you are using bash then we'll want to copy that SSH command from our networking tab in the note and we'll paste that into our command line now I have two different terminal windows opened up here now one of these I'm going to use to run commands on my local machine and what our remote Linode server now you don't have to do it this way but if you only have one terminal window open then you'll have to go back and forth between your local machine and your server so I think it's easier to simply have two windows open ok so I'm going to paste that SSH command here into the terminal on my left side and we can see that this does an ssh of our root so that's the root user at this IP address now yours is going to be your IP address for your server and then it's going to ask us if we want to continue the connection it's only going to ask us the first time that we do this so I'll say yes and now it's asking for that root password so this is the root password that we created when we created our node so mine was this is a test and I'm going to delete the server after the video so you can't you know log in to this IP address with this root password or anything like that ok

### [8:51](https://www.youtube.com/watch?v=goToXTC96Co&t=531s) Setup Flask Server

so now we are connected to our load server so this is the machine that we just created now just to get some more room here I'm gonna minimize this terminal here on the right and expand this over to where we have some more room to work with here okay so now we're working with a bare-bones a boon to server so we're gonna want to do a couple of things to get this set up first so first of all let's upgrade the software and this is going to be like security updates and stuff like that you're gonna want to always do this the first time you log into a Linux system so I'm going to do apt update and then these two ampersands and apt upgrade and that's just going to update and upgrade the software on the system so some of these updates can take a long time so I'm just going to fast forward the video until this is complete and you're occasionally going to be asked if you want to continue and I'm just going to hit yes any time those come up okay so I fast forward to where those updates and upgrades were complete and that took a couple of minutes so now we're gonna want to set our hostname on this machine so I'm gonna clear my screen here and now to set this hostname I'm gonna say a host name CTL set - host name and I'm just going to call this flask - server so now if I actually type in a host name then it should say flask server there so that's good so now we also need to set this host name and our hosts file so to do that I'm just going to use the program Nano since Nano is an easy editor that a lot of people know how to use so I'm just gonna say Nano ford slash etc' ford slash host and within this host file we're going to want right under our one 2700 dot one we're going to want to put in our IP address of this machine so I said to write that down because you're going to be using it a lot mine was 40 5. 30 3. 1 to 3. 2 1/4 and after that then we're gonna want to hit tab and then put in our host name again so I called mine flask - server and now to save this in Nano you hit control X to exit and then it's going to ask you if you want to save so I'm gonna hit Y for a yes and then the file name that you want to write if you just want keep the same file name then you just hit enter so now that saved that host name to our host file okay so now let me clear my screen here now we're going to

### [11:16](https://www.youtube.com/watch?v=goToXTC96Co&t=676s) Add a Limited User

want to add a limited user to our machine so right now we're logged in as the root user now the root user has unlimited privileges and can execute any command now that might sound nice but it's best practice to add a new user that has limited privileges that you use as your main account and you'll still be able to run admin commands using sudo it's just a lot more safe than running everything as root so to do this we can just say add user and now the username of the user that you want to add I'm gonna add mine as core EMS but you want to add whatever yours is here now again okay so now it's asking us for our password so I'm just going to put in something like this is a test and now it's asking us to fill in some information about our user now this is optional you can put this in if you'd like so you know full name I'll put in my full name but I'm just going to leave like the room number and all that other stuff blank then it's going to ask you if that's correct and I will just accept the default as yes so let me clear the screen here again now again I did use a

### [12:27](https://www.youtube.com/watch?v=goToXTC96Co&t=747s) Add User to Sudu Group

boon to as our operating system so if you used something different something like CentOS or red hat or Fedora then these commands are going to be different so just keep that in mind okay so now that we've created that user now we're gonna want to add that user to our sudu group so that they can run those admin commands so I'm going to do add user core EMS and then after that do sudo and that will add them it says here adding query MS to the group su do so that's good okay so now that we've created this new user now we're going to want to log out of the our server and log back in as that user because we don't want to be logged in as root longer than we have to it's just best practice be logged in as a limited user so I'm going to exit out of our server and now I'm back on my local machine so I'm just going to hit the up-arrow to run that same SSH command that we ran before but instead of route we are going to log in as the user that we created so I'm going to log in as query MS and it's going to ask us for a password so that was this is a test and now we are logged in as the new user that we created so now I'm going to clear my screen here

### [13:46](https://www.youtube.com/watch?v=goToXTC96Co&t=826s) SSH Key Based Authentication

okay so now that we're logged in with this new user we're going to want to set up SSH key based authentication so that we can login to our server without a password so at this point I know that some of you might be thinking to yourselves like you know why do I have to do all of this stuff I just want to deploy my flask application well the reason that we're doing all of this is because you know a lot of people had requested to set up a linux server from scratch and this is what it's like to deploy a real-world application and to put the proper precautions in place on your web server so that includes best practices like setting up SSH keys and firewalls and you're going to want to do that on any real-world application that you deploy so I may as well include it in this tutorial instead of just showing you the bare minimum so when it comes to these SSH keys by default we're using a password to login to our web server just like we just now did we instead want to used key-based authentication so this is more secure and also more convenient because it uses keys that can't be brute forced and it also uses allows us to log in without putting in our password every time which is great for running remote scripts that connect to your web server now I have a separate video on this ssh authentication as well so i'm not going to go into a lot of detail of these commands but we are going to run through all of the whole process here so if you want to know more details about what these commands are doing then you can watch that video and i'll put a link to that in the description section below now there's actually an easier way to do this by using a command called ssh copy ID but it's not available on all operating systems so instead we're just going to do this the longer way so on our server here we're going to want to make a dot ssh directory so I'm here in my home folder if I do a PWD you can see that we are within home and then our user so mine is query MS now this tilde here is just an alias for our home directory so that's it one way that you can tell that when we are in our home directory so within our home directory I'm gonna make a dot SSH directory so I'm gonna say m'kay Durer and I'm going to make a directory called dot SSH okay so now I'm going to stay logged in to my server but I'm going to open up the terminal on my local machine so now I'm

### [16:07](https://www.youtube.com/watch?v=goToXTC96Co&t=967s) SSH Key Generation

going to move this over here so now I'm on my local machine not on my server now again I'm doing this in bash but if you're using a program like putty on Windows that we talked about before then you'll have to do this differently to create and copy your SSH keys to your web server and I did find some documentation in the notes guides for putty users on how you can do this through putty and I'll put a link to that in the description section below so that you can follow along with this part so you can use that guide if you need it but if you are using bash then we can simply say SSH - key gin and then I'm gonna do a dash B 409 6 and that's just to make it a little more secure so now it says it's generating the public private RSA key pair enter the file in which you wish to save this and it gives a default file here I'm just gonna leave that default file and it says that there's one already there because I already have some SSH keys I'm just going to overwrite that for this tutorial and now it says to enter a passphrase now you can leave an empty passphrase which I'm going to do but if you want to make it more secure than you can use a passphrase for your key ok so now that we've created that it says that your identification has been saved and we got this ID RSA file and we also got this idrs a dot pub that is our public key now we're going to want to move our public key to our server so to do this I'm going to clear my screen here to do this on bash I'm going to use the SCP command which I believe stands for secure copy so I'm going to say s CP and the location of that public key if you use the default location is going to be in your users home folder dot SSH and forge / ID underscore RSA dot pub and we want to copy that public key up to our server so now I'm going to say Corre ms @ and now the IP address so you want to put in your IP address here mine is for 5. 30 3. 1 to 3. 2 1 4 so that is the user and the server to where we want to copy that key now if we want to copy it to an exact location on that server then we can put in a colon here and now specify that exact location so I'm gonna put a tilde for the home directory of this user and so a tilde ford slash dot SSH and I want to save that public key into a file called authorized underscore keys now you don't need file extensions on Linux so this is a valid file name here we can just call it authorized underscore keys so I'm going to run that and this is going to ask us for our password because we haven't set up our SSH keys yet so I'm going to say put in my password here and we can see that it copied that key up so now I'm going to minimize this terminal

### [19:11](https://www.youtube.com/watch?v=goToXTC96Co&t=1151s) SSH Permissions

window here and go back to my server so now in my server I'm going to see if that file is there so I'm going to do an LS on the dot ssh directory and if i do that we can see that we now have this file here called authorized keys and that should be the public key that we copied up ok so now that we've got that copied up now we need to update some permissions and again I can't go into deep detail as to what every command is doing in this video or else it would just run on for a long time but basically what we're going to be doing here is setting the permissions for the SSH directory to where the owner of the directory has read write and execute permissions on the directory and the owner of the files in that directory will have read and write permissions on the files so to do that I'm going to do a sudo chmod that's how you change permissions and I'm gonna do 700 permissions on the dot SSH directory in my home folder and it's going to ask us for a sudo password this is just gonna ask us this one time every so often we're not gonna have to put that in every time we run a sudo password because it'll remember us for some time so now I'm also going to do a command here where I'm gonna do a sudo chmod 609 to go into deep detail about this here but basically what these permissions are in Linux the first digit here are the permissions for the owner of that file the user who owns that file so we have a seven here which means read write and execute now the second one here we have a zero means no permissions that's for the group of that directory and the last one here is for everyone else and that's a zero as well and here we're saying that we want 600 permissions for the owner zero permissions for the group and zero permissions for everyone else on the files in that directory okay so with those changes in place we should now be able to log in to this server without a password and instead it's going to use our public and private SSH keys so if I exit out of the server here now we're back on our local machine now I'm going to clear my screen I'm just going to hit the up arrow here to where we to run the same SSH command that we did before and if I run that then we can see that I was able to SSH into that machine without a password so that is a good sign that means that we're using our SSH keys okay

### [21:47](https://www.youtube.com/watch?v=goToXTC96Co&t=1307s) Password Authentication

so we're just about ready to start moving up our flask application but there's just a couple more things that we need to do here so now that we have our SSH keys working we also need to disallow root logins over SSH so now that we're logged in as our user let's do a an update on this SSH config file so I'm going to do a sudo nano and this is within forge slash et Cie forged slash SSH forged slash sshd underscore config so if we run this put in my pseudo password here so this is the ssh configuration file so i'm going to scroll down here and we're going to want to change two values in this configuration file so first we want to scroll down until we see one option here that says permit root login we're going to want to change this to no because we have a limited user now that has pseudo access so there shouldn't be any need for us to log into our machine as root so if a hacker tries to log in as root we're going to know that hey you don't need to be able to do that so with that set now let's also scroll down and we're gonna look for one called password authentication so let's keep scrolling down here and here it is here it's most likely going to be commented out so I'm going to uncomment out this here and I'm gonna change this from yes to no so the reason behind this is that now that we have our SSH keys working sometimes hackers will just you know simply try to brute-force passwords but since we have our SSH keys we shouldn't have the need to log into our system with a password so I'm going to put password authentication to know so now to save this I'm just going to hit control X and then a Y to save and then enter to keep

### [23:43](https://www.youtube.com/watch?v=goToXTC96Co&t=1423s) Firewall Setup

the same file name and now we want to restart our SSH service so to do that we can say sudo system CTL restart and that's sshd so let's run that and that restarts our SSH service okay so now before we get to the flask deployment we are going to set up a firewall but this is going to be very quick here this is pretty simple so first we want to do an installation so I'm going to say sudo apt install and this is called ufw and this stands for uncomplicated firewall so I'm going to run that and once that's installed we're going to set up a few rules here now this is called uncomplicated firewall because this is a lot easier than some of the other options like IT tables or anything like that so the rules that we're going to set up we're just going to do a pseudo UFW default allow and we're going to allow outgoing traffic so I'm going to run that and now I'm going to hit the up arrow here and do a pseudo ufw default deny incoming traffic so now we want to configure a default deny rule or I'm sorry we're going to want to configure allow rules for certain ports because configuring a default deny rule like we just did can lock you out of your server unless you use explicit allow rules so we want to be sure that we have configured these next allow rules to allow for SSH and HTTP and things like that and any port that we want to access from the outside of our server so I'm gonna say sudo ufw allow SSH now this one is definitely important because if we don't allow SSH then we're not going to be able to SSH into our server so you definitely want to do that one so now let's also allow access to port 5000 for now port 5000 if you remember from earlier in the series is the port that flask development server runs on so we're going to test this before we actually go live with it on port 80 so let's allow that port 5000 so that we can test that on that port so I'm going to do a sudo ufw allow 5,000 and now let's not allow port 80 or HTTP traffic yet until we're sure that everything's working the way with it we want it to and we will allow that port later in the video so right now I'm going to enable everything that we have just said so I'm going to do a sudo UFW enable and run that and it says that the command may disrupt existing connections hopefully we remembered to allow SSH connection so I'm just going to say yes okay so we're still logged in so that's good now if you want to see the status of the things that you've allowed and disallowed you can go to sudo UFW attis and that'll show you everything that we've allowed so port 22 here is SSH and we also have port 5000 here ok so that is all of the server setup type of stuff so now we're ready to deploy our flask application so first we want to put our application on our web server now there are multiple ways that we can get this application to our web server so if we have it checked into a git repository then we could simply do a git clone here into our server if you're using an FTP client like filezilla then you can just simply copy it over to your server since we're already using the command line in this video I'm just going to use the bash terminal to do this so I'm going to clear my screen here on my server and now let me open up my terminal here on my local machine now before we push our flask application to our server if we're using a virtual environment then we're going to want to create a requirements txt file that captures everything that we need to install for our flash project to work so I am in a virtual environment here on my machine this is the virtual environment

### [27:50](https://www.youtube.com/watch?v=goToXTC96Co&t=1670s) Virtual Environment

that I used throughout the entire series if you're not using a virtual environment then you'll just simply have to pip install everything that you used on the server manually but if we are using a virtual environment then we can see everything that we use in our project by running pip freeze if we run pip freeze then this shows us all of the dependencies for our project that we've installed so you can see here we have bcrypt we have flask obviously we have flask WTF which is the forms Jinja 2 which is the templating pillow which does our images and these also give us the exact versions of those packages as well so that we're sure that everything on our server matches every packaged version in development now if you're on Windows then you can create a requirements txt file and just paste in all of the info from this pip freeze command but if you're on Mac or Linux

### [28:44](https://www.youtube.com/watch?v=goToXTC96Co&t=1724s) Requirementstxt

then we can just create our requirements txt file by saying pip freeze and then we can put the Khan hence of that pip freeze command into requirements that txt okay so now I just created this requirements txt file on my machine and I'm in the home folder of my machine here so I'm gonna open up my file explorer here and open up both of these windows so this is my home folder here and here's that requirements that txt file and here is my flask blog this is our flask project that we've been making throughout this series so I'm just going to drop that requirements txt file into that flask blog okay so now that we have that requirements file now let's put our flask application on to our webserver now since I'm using bash I'm going to use the same SCP command that I used earlier to copy up our keys but if you're not using bash then again you can use something like FileZilla or get to get your project folder onto your server but for me I'm simply going to say SCP - R that's for recursive that means that we're going to move over an entire directory so I'm gonna say - R and that is what this is on my desktop so on my desktop flask blog I'm just going to move over that entire folder and we're gonna move that to quaerimus at and now the IP address so you're gonna want your user here and now your IP address my IP address is 4 5. 3 3. 1 to 3. 2 1 4 and now we want the colon and the colon we can specify an exact location for on this machine so I'm just going to put it in that users home folder by saying tilde ford slash so let's run that okay and it looks like it copied everything over for us so now let's check that that's there on our server so I'm going to minimize our local machine here and go back to our server so you

### [30:52](https://www.youtube.com/watch?v=goToXTC96Co&t=1852s) Creating a virtual environment

can see how this is useful having these two windows open because otherwise you'd have to be exiting an SSH edging back into your server and local machine all the time okay so now that we're back on our server here let's run the LS command to see if we have our directory so we do have our flask blog here so that's good so now we have our flask application on our web server so now we're ready to get it running on here so first in order to do this we're going to have to create a virtual environment on our server we don't want to use the default Python that's running on our Linux system we always want to use a virtual environment when running on our server so to do this we're going to want to install a few things so I'm going to say sudo apt install and we want to install Python 3 - pip now make sure you have the 3 there for Python 3 otherwise it will install for python 2 so we're gonna do the sudo apt install python 3 - pip and once that's finished I'm going to clear my screen here and now I'm going to install sudo so I'll do a sudo apt install and I'm going to install Python 3 - ve + V and this will allow us to create virtual environments so let's run that and this should install fairly quickly ok so now that we have those two packages installed now we can create our virtual environment so I'm just going to create this virtual environment inside of our flask project so I'm gonna say Python 3 - M V in V and this will create a new virtual environment now we just have to specify where we want that virtual environment so I'm going to put this within flask blog and I'm gonna call this virtual environment ve and V so I will run that command and that should have created that virtual environment so let's check so I'll do a CD in the flask blog and now we do an LS we can see that we have our you know project directory flash blog our requirements file run dot PI but we also have this V env directory so that's our virtual environment so in order to activate that we can simply say source V E and V Forge slash bin forge / activate so I'll run that and now our virtual environment should be activated and a good hint is here at the beginning of our prompt in parentheses here it says V env so our virtual environment is activated so with that activated we can now install all of our requirements for our project so in order to and stop install all of the dependencies from the sort of crime at txt file we can simply say hip install - R and after we do the - our we put the path to the requirements txt file so it's just here in the same directory so I can just say requirements txt so if I run that then it's going to install everything that we need for our application okay so that should have installed all of the Python packages that we need for our application so now we want to test our website using the development server and make sure that it works using that development server before we install nginx and G unicorn but before we test this there are a couple of variables that we first need to set so if you remember on our local machine we set some environment variables for our secret key our database URL our email user and our email password for our password resets and we're going to need to set those on our server before our application will work properly now on our local machine we used environment variables and we could use environment variables here as well but I think that sometimes environment variables can be a little tricky when working with different web servers so instead let's just create a configuration file with all of our sensitive information and we'll load that into our application instead of our environment variables so first I'm going to go back to my local machine and grab the values of those environment variables so that we can add them to our server so I'm going to clear my screen here on the server and now I'm going to open back up my local machine here now

### [35:12](https://www.youtube.com/watch?v=goToXTC96Co&t=2112s) Getting the environment variables

there are a couple of different ways that we can get those environment variables now if your flask environment is activated then you should be able to grab all of those just by using Python so I'm just going to put Python here to open up our Python command line and now I'm going to import OS and now we want to grab our secret key so I'm gonna say Oh s dot environment and we want to get that secret underscore key so that is the secret key that we used for this project so now I'm going to want to do the same thing except I'm also going to want the SQL alchemy underscore database underscore URI so let's run that now if you're wondering what all environment variables you need we set all of these in our flask configuration file so if you look in that flask configuration file you should be able to see where you're using these environment variables it should say oh s dot environment or dot get and then secret key sqlalchemy database URI and etc now we also need to grab our email user so email underscore user and also our email underscore pass so my email user is just my email address now my email password I'm not going to actually hit enter here and show my email password for obvious reasons I don't want people to be able to log in to my email but our off-camera I'm going to grab this email pass value here as well and put this within the configuration on my server okay so now that I have these printed out here I'm going to go back to my server and I'm

### [36:56](https://www.youtube.com/watch?v=goToXTC96Co&t=2216s) Creating the config file

going to create a config file so I'm going to say sudo touch and touch will create a file I'm going to create this in forge /e TC ford slash config dot JSON now I'm calling it config dot JSON because this is going to be the only flask application that lives on this server if you need to differentiate between multiple flask applications then you could call this you know flask blog config or something like that instead then I'm also using JSON for this file but if you're more comfortable using Gamal or something like that then you can use that as well so I'm going to create that file and now I'm going to edit that file so sudo nano - et Cie config dot JSON fig JSON okay and within this file we're going to create JSON here so we need these opening and closing curly braces and first we want to create a value for secret key so the value for our secret key that needs to be in double quotes I'm going to go back to my local machine here I'm just going to grab that value from our local machine and go back to our server and paste that in and then put in a comma here and now I will do the same for I'm actually going to copy this key because it's a long one SQL alchemy database URI let me move this over just a little bit here okay so I will paste that in for the key and the value for that key was let me move this over a little bit here the value for that key was just our simple SQL Lite database so I will paste that in and don't forget your comments here after these key value pairs in your JSON so now we need our email user and our email pass now you're going to put in your email user here and your email pass now I'm not going to put those here in this video because that is sensitive private information for myself but off video I'm going to put those values in so that we can see how the password reset functionality works on our server so I'm just going to save this file so I'll hit ctrl X Y to save and then enter and now I'm going to pause the video and go back in to that config dot JSON and I'm going to put in my email username and my email password so that functionality works here the server I'm just not gonna show it on video so I will resume the video once I finish with that okay so I went back in

### [39:42](https://www.youtube.com/watch?v=goToXTC96Co&t=2382s) Editing the config file

that config file and I put my email user and my email pass so now whenever we test this that reset password functionality should work with our email service okay so now that we've created this config dot JSON file now we're going to want to edit our config file in our flask project and set those values so I'm going to do if we do an LS here on our flask blog you can see that this flask blog directory here contains our other project files so I'm gonna do an LS on flash blog and you can see that is where our config PI file lives so I'm going to edit that file so I'm gonna do a sudo nano flash blog config dot PI and within this file here at the top I'm going to import JSON since we're now using JSON instead of environment variables and also here at the top I'm going to load in those values so I'm going to say with open and we're going to open that file that we just created and so this is the path so as in 4/8 ici ford slash config dot JSON and we will open that as config underscore file and now within here we will say config is equal to json dot load and load in that config file now when you use JSON load on a JSON file what that doesn't Python is it makes this variable here a Python dictionary so now this Python dictionary called config is equal to all of the key value pairs from our JSON config file so now here at the bottom parts of our file let me scroll up here a little bit everywhere that we're using environment get we can now use config dot git since config right here is a dictionary with those configuration values so instead of OS not in firing I'm going to say config dot git so we're doing config dot git on the secret key we're going to do a config dot git on the SQL alchemy database URI and we are going to do a config dot get on the email user and on the email pass okay so once that is done I'm just going to save that file so since I'm using nano that's control X Y to save and then enter okay so now we're ready to actually test our application and see if it works on our server so there are a couple of ways we can test the application let me clear my screen if you remember we can do a if I do an LS here on our project we can see we have this run dot pi if you remember I usually do this Python run PI but if I do a cat on that file and print out the contents of that file then we can see if I run that then it's just going to do an app dot run of debug equal true but I actually want to set our host equal to zero zero and what that'll do is that will expose it to the outside world so to do that instead of doing python run pi i'm just going to do like we saw earlier in the series and I'm going to use flask run now if you remember in order to use flask run I have to do an export of our flask project so I'm going to do an export and this is just going to create a temporary environment variable so that we can test this so I'll say export flask underscore app is equal to and there's no spaces here so is equal to run dot pi because that is what contains our application so now that we've done that export flask app equals run dot pi now I can simply do flask run now don't hit enter yet instead of doing flask run we also want to set the host so I'm going equal to 0 0 and that will allow us to access this development server from the outside so from our browser so I'm going to run that and it should spin up our server so we can see that it's running one our IP address one port 5000 so now if I open my browser here then whoops let me actually open up my other browser here so now I want to go to my IP address at port 5,000 so my IP address you're going to want to use with yours mine was 4 5. 3 3. 1 to 3. 2 one 4 now if we just go to that IP address then we're not going to get anything because port 80 currently isn't open on our firewall so you can see it says the site can't be reached so to go to a specific port we want to put in: 5,000 to go to port 5,000 if I run that then you can see that we get what seems to be our application ok so it looks like our application is working but we're always going to want to do a little bit of testing here so to make sure that the functionality is working let's try a couple of things so let's go to login and see if we can log in as a current user so I will try to log in as my Cori em Schaefer user it looks like that worked logout that seems to work let's go to register and try to create a new user so I'm going here and just call this deployed user for the email I'll do deployed user at test comm password I'll just do testing password testing signup and that seemed to work so now let's try that so deployed user at test comm testing to log in that seems to work let's try to create a new post deployed post and I will copy that and post that so it looks like that worked see if we can update a post updated deployed post that works let's try to delete a post so if I delete a post that seems to work as well let's see if we can change our profile picture so right now we just have this default profile picture I will try to choose a new picture here just choose one from my desktop update that and that seemed to work okay that's good and let's also test that our email is working so if I go to login forgot password if I say that I forgot my password for my Cory M Schaffer gmail account if I run that then it says an email has been sent with the instructions and reset your password I actually have my gmail opened up here and we can see that I got the password reset request here so if I click on that then we can see that I got my password reset link and I can now change my password so instead I'll change that to testing one two three instead of just testing and if we log in with that new password testing one two three then that seems to work okay so everything all of our functionality for our website seems to be working so that's good but if we go back to our server here we are running a development

### [47:23](https://www.youtube.com/watch?v=goToXTC96Co&t=2843s) Installing Nginx and G Unicorn

server on our live production server this is not what you want to do this is great for testing but you don't want to go live with this and send this URL out using a development server it's a development server for a reason it's not meant for you know a lot of performance and to be hit by a lot of people so that's why would you use something like engine X and G unicorn because those applications are you know do allow for high traffic and for good performance so now we're going to want to get our application working with engine X and G unicorn but this is a very good sign that it's currently working in our development server so now I'm going to contain control C and clearing my screen here and now let's install nginx and G unicorn so I'm going to CD back to my home directory just so I have more room here to work with and now I'm going to say sudo apt install and we're going to want to install engine X so let's run that and once engine X is installed then I will clear my screen here and now we want to install G unicorn so we can actually install G unicorn with pip so I can do pip install now you're gonna want to make sure that you are still within your virtual environment here so make sure that you haven't deactivated that because we'd want to install gene unicorn in that virtual environment so I'm going to do a pip install G unicorn so we will run that okay and once that's

### [48:56](https://www.youtube.com/watch?v=goToXTC96Co&t=2936s) Updating Engine X Configuration File

installed we just need to change a couple of configurations with nginx and with G unicorn and we will be done so first of all we're going to update the configuration file for engine X so the way that engine X and G Unicorn work together is that engine X is going to be our webserver and it's going to handle the requests such as static files and things like that it's not actually going to handle the Python code it's going to use G unicorn to do that so we're going to allow engine X to handle you know like the static information like the CSS files and JavaScript and pictures and things like that but when it comes to handling Python code we're going to pass that off to G unicorn so in order to do this first let me clear my screen here first let's remove the default engine X configuration file so I'm going to say sudo RM and this was is in ford slash et Cie engine X and sites enabled sites - enabled and default so we're just going to remove that default file and now we're going to create a new file so this is going to be sudo nano and we will in /e TC forged slash nginx porch last sites - enabled and we will call this flask blog so let's run that this is a new file this doesn't exist yet so it's going to be completely blank so now to create an engine X configuration file we're just going to say server and then in these curly braces here we will say listen on port 80 and you're going to want to remember these semicolons here I know that Python code we're not used to putting in semicolons but here you have to remember that so now we need server underscore name and that is going to be equal to four now it's just going to be our IP address so my IP address you're going to want to put in yours mine is four 5. 33 dot one two three two one four semicolon and now we're going to forward all of our static files so our CSS and JavaScript and our pictures and stuff like that we're going to let nginx handle that but we need to tell nginx where those are located so I'm going to say location ford slash static and then another pair of opening and closing curly braces so for location static that is going to be alias so alias to ford slash home and then your user name my user name is corey ms but you want to put yours and then your project - flask underscore blog and now the location - our static directory so within that flask blog directory I have another directory called flask blog that holds our project files and then there's a static folder within there so you're going to want to put the location to your static folder but it should be something like that if you've been following along with this series okay so having that in place now we're ready to forward all of the other traffic to G unicorn so now we can say location and just do a ford slash and then some opening and closing curly braces here now I am going to put this file this engine X configuration file I am going to put this on github if you're worried about miss typing any of this so I will have this up on github so that you can use that as a reference okay so at this location here at this root location basically this means if we go to our IP address then this is what's going to happen so we're going to do a proxy underscore pass and then we're going to pass this off to G unicorn now by default G unicorn runs on port 8000 so I'm just going to say do a proxy pass - HTTP forge / localhost so our localhost is the server in this case on port 8000 so that will forward all that traffic to G unicorn and let that handle the Python code now there's also a couple of other things we're going to want to add in here that just passes some extra variables for that proxy so to do this we're just going to say include and we're going to want to include this file here /e TC flurried / nginx forge / proxy underscore programs and put a semicolon there and then we will also do a proxy underscore redirect off and then a semicolon now there are all kinds of things that nginx can do if you want to know any more details about any of this stuff then I would highly suggest looking at the engine X documentation and it'll explain in more detail what a lot of this stuff is doing but this should be good for our engine X configuration file so I'm going to save this so since I'm using nano I hit ctrl X Y to save and then hit enter okay so

### [54:04](https://www.youtube.com/watch?v=goToXTC96Co&t=3244s) Enabling Firewall Allow

in our engine X configuration file we said that we were listening on port 80 so if you remember we haven't actually opened up that port on our firewall yet so let's go ahead and do that now so I'm gonna say sudo UFW our uncomplicated firewall allow and we will allow HTTP TCP traffic so it said that it added those rules and since we are done with our testing we will also disallow any traffic on port 5,000 since that was our testing port so I'm going to say a sudo ufw delete and I will delete the allow of port 5,000 so again I'll make sure that is enabled so sudo ufw enable and hit Y for yes okay and now we want to restart our engine ax server so I'm going to say sudo systemctl restart engine X okay so that restarted our nginx server so now I'm going to clear my screen so now our engine X server is running but G unicorn is not running so our server is not going to know how to handle that Python code so if I go back to my browser here and I try to reload this page then it's not going to work so if I just let this spin up here it'll give me an engine ex-air eventually and I'm actually still on port 5000 here so that's not going to work at all and actually instead of using regular Chrome here I'm gonna go back to using my incognito because incognito if you don't know it doesn't cache things like h or CSS and things like that so it's easier for development so if i run that then you can see that we got a 5 i too bad gateway and we can see that this is an engine X error here now that is because it's listening on port 80 so we got in contact with nginx but it doesn't know how to Ford Python code so we have to run G unicorn so the engine X Forge this request to G unicorn and then G unicorn knows how to handle that Python code now we can access our static files so if we try to access like one of our CSS files I can go to forge slash static forward slash main dot CSS that should be working because that is just nginx handling that information so we can see that we can see our CSS code here so that works but we need to run G unicorn in order to get the Python code working so let's go back to our server here and now let's get GE unicorn working now to run G unicorn it's actually a very simple command we can just run G unicorn and then we can also run some workers here so I can say dash W and then the amount of workers so I can say three and then we want to specify the file that has our application so the module that contains our application variable is run dot PI so we can just say run and then a colon and then the variable name of our application so the variable name in our application is app now I'm not going to run this yet because I actually have to change directories here but first of all let me also explain the workers here so a lot of people say ok how many workers do I need to run for my machine well if you look in the G unicorn documentation then they say that the number of workers should be two times the number of cores on your machine plus one so in order to see the number of cores on your machine it's pretty easy to figure that out in Linux one way you can just do an in Prague - all and remember we got the Nano done of the node here which is your cheapest version so I just have one core here so that's why I chose three workers because that is two times our number of cores which would be two plus one so that's how you figure that out if you're interested okay so in order to run G unicorn here I'm going to actually CD back into my flask blog and now if I do an LS we can see that we have run PI here now let me cat out the contents of that file and you can see that within run PI we have app equal to our create app and that's what creates our flask application so to run that G unicorn code again it's G unicorn and I'm going to use three workers and that is within the run module and that variable for our application is app so if I run that then we can see that it says that it's listening on our localhost at port 8000 and that it booted up three workers for three different processes so now if we go back to our browser here and reopen this in our browser you can see that now we are just going to our IP address and nginx is forwarding that traffic to G unicorn and G unicorn is handling this Python code so now our website is working in production okay so I'm not going to go through all the same tests that I did before but we can see if I just you know try to log in we can see that at least that is working so it seems to be working well so far but there is one more thing that we want to do this isn't quite ready for production just yet because if we looked at our server you know this isn't really good the way that this is running here because this is running in the foreground we can't do anything on our server here this has to remain open so if I was to close my server so if I hit control C and stop that then we just killed G unicorn and if I run try to reload the page this isn't working anymore so what we need is something that is constantly monitoring G unicorn and making sure that it's running and will auto start it and auto restart it if it crashes and things like that so in order to do that we're going to use some software called supervisor and this is very easy to use on Linux so to install supervisor I'm just going to say sudo apt install and this is called supervisor so let's run that and install that I'll say yes ok and once that is installed we just need to set up a quick and easy configuration file for supervisor so to do this will say sudo nano and this is going to be in /et see Forge slash supervisor conf dot D and within comp D we're going to create a configuration file so this is going to be flask blog. com sorry that this is running on the other line here I know that makes it hard to read but I called this flask blog. com so if we run that then now we have a blank configuration file here and I'm gonna put this file up on github as well but to create a supervisor configuration file here first we can just put these square brackets first we want to say program and the name of our program so I'm just going to call this flask blog and now we want to put in a few variables here so I'm gonna say directory so directory is where this is going to run a certain command from so we want to run a command from our flask project so this is in fort slash home slash CMS you're going to want to put your user name there and mine is called flask underscore block and now we to put in the command that we want to run so from that directory is G unicorn with three workers and then run app now if you remember G unicorn is actually in our virtual environment and we're not going to activate the virtual environment here from within our configuration file so instead you're going to want to put in the full path to G unicorn and that is just within the bin folder of your virtual environment so this is gonna be a little long here but this is within our home directory of our user and that is within flask blog is where I put that virtual environment and that virtual environment is called V E& V and within the bin folder of that virtual environment that is where the G unicorn command lives so we want to run that command with three workers so I'll say - W three and remember that is just we want to run that on the run module and app is the name of our application so now a few more things here we'll say user is equal to core EMS we want to do an auto start equal to true that means that the that supervisor will make sure that this auto starts we'll set an auto restart equal to true that is if it crashes for any reason then it's just going to start it right back up now we also want to do a stop as group make sure that spelled right equal to true and a kill as group that's just going to help you know if we stop or kill this it's going to help wrap up any child processes now we also want to do some air and log files here so I can say st de r so standard air underscore log file is equal to and we will create this log file in a second but we will put this in ford slash bar /log ford slash flask blog ford slash let's say we'll just call this flask blog dot e RR dot for our error log and I'm going to just highlight this and copy it so I don't have to type all this out again paste this in and for our standard out I'm just going to call this class blog dot out dot log and back here at the beginning this is going to be the standard out log file okay and that is it and again I'm going to put this on my github repository if you want to check and make sure that all of this looks good if you want to you know look at this on the github page so I will hit control X Y to save and hit enter and now we want to create those log files really quick so in order to do that I'm just going to say sudo make Durer and I'll do a - P will create any directory in the chain if none of them exist so I'll say - bar - log - flask blog and now we called those log files so I'll do a sudo touch we called those that was within port slash var slash log flask blog we called that flask blog dot e RR dot log so I'll run that and I'll hit the up arrow here we also want to do flask blog dot out dot log so I'll run that okay so now that I have all of that in place I'm just going to restart our supervisor so in order to do that I'll just do sudo supervisor CTL reload so if I run that we can see that it restarted supervisor so now if we reload our page in the browser here sometimes it can take a while for a supervisor to start up that process if I run that now we can see that it's already working so now if you wanted to then you could go through and check that make sure all of this you know functionality is working correctly so you know if I go in here and change some pictures and try to update this we can see that works we can create new posts so if I run that new post we can update and it's always good to check this functionality just to make sure that nothing is off so one thing that you might notice here if I go and change my profile picture now that we're using nginx as a webserver engine X has some defaults that you might not expect so you could get some unexpected things with your application and that's just kind of knowing your webserver so for example if I choose a really large file here so I have a file on my desktop called large JPEG if I open that and I try to update that as my profile picture if I do that you can see it's gonna spin here for a little bit and then it's going to give me an inch and X error and it says four one three requests entity two large now this is an engine X default it won't accept client you know upload sizes over I think it's two megabytes and I think that to that picture is 2. 8 megabytes now if you want to change this you might not even have that need for your application so if you don't have the need then that's completely fine but if you do have the need and you need to change that then here within our server I'm gonna clear the screen here you can update that by going to sudo nano that's in forge /et c ford slash engine x forge slash nginx kampf so within here if we scroll down to HTTP then I am going to just come in here past at the bottom of the basic settings here and you can just set a variable called client underscore max underscore body underscore size and I'm just going to set that to five megabytes so you can set that to whatever you want to set it as if you remember the application that we created in this video automatically resizes large uploads to a smaller upload anyway so I will save that and then you can restart engine X by doing a sudo system CTL restart of nginx so now if I go back to my account page and try to upload that same large file again then we can see that this time it worked and if I open the picture in a new tab then we can see that it's a small picture anyways because our web application that we created takes those large images and resize sizes them down to I think 125 pixels is what we chose okay and real quick just to make sure that the password reset is working as well you know that's something that is easy to not work sometimes so I can go to forgot password type in our email address and request that password reset so if I open up my email address here so I'll go back to my inbox and we can see that we have a password reset and go there and that whoops let me click on that reset link help and I don't think that worked because I was still logged in here when inside of this browser so if I log out in that browser and then go back using that reset link you can see that now that works so testing one two three yeah so that seems to work okay so let me go back to our home page here so now that we're using supervisor if I completely log out of my server so I'm back here on the server if I just go to exit and I can just close down my all of my terminals completely if I close all of those down then we can see that I can you know do a hard refresh on my pages here and this is all still working so we have a completely functional website that is working on our IP address that is fully deployed at this point now there's still a lot more that we could do in future videos if you're interested so right now we only have an IP address but if you want then I could also walk through the process of buying a domain name and how to get that domain name to go to this server that we've set up we could also see how to add SSL certificates so that we can have an HTTP domain name that's actually something that I still need to do for my personal website as well I'm still using HTTP now I'm actually going to delete this server after this video so if you go to this IP address here then you're not going to see this website so if you go to this IP address then that's why you won't see this so if we do continue this series then I'll spin this server back up with a different IP address when I record more videos for this series now actually let me go ahead and delete this server on this video so that if you're following along then you can do this as well so that you're not charged for it so let me go back here to my Leno to probably need to log back in no it looks like I'm still logged in here so that's good now if you want to completely delete your server then you can just go to your lenosky R and over here on the right you can click on this settings menu here and you can go down to settings and once you're at settings you can see at the bottom here we have delete the node so you could click on delete and then it's going to ask you are you sure that you want to delete this because it's going to result in permanent day loss everything that we did in the video is going to be done so you can delete by clicking that there I actually think that I'm just going to power this off for now so I'm just going to say power off instead and I will delete that later now like I said at the beginning of the video the node was actually kind enough to sponsor this video and I've used them for many years and have recommended them the people long before I even had any sponsors so if you get a chance I would highly recommend giving them a shot so like we saw earlier in the video they have this new and improved cloud management system that makes spinning up a server fast and easy you can choose from available images and you can even upload your own custom image if you'd like and if you're doing something that's fairly common they even have stacks scripts that allow you to spin up a server with all of the relevant software already installed and ready to go so for example if you're making you know like a WordPress site or something like that then you can simply choose their WordPress stack script that spins up a server with WordPress ready to so if I was to click here on the node and then here at create an image if I instead go to create from stack script and then go to the node stack scripts we can see that their WordPress stack script is the top one here and it says a ready to rock WordPress install using the latest release from wordpress. org so that is pretty neat that they have these images that are just ready to go like that look and it looks like I need to log back in here now they also have nine worldwide data centers so far and they have two more set to open in 2019 so no matter where you are you should be able to spin up a server close to your audience so if you want to check them out then feel free to use my referral link in the description section below and you can get $20 of free credit applied to your account to try them out okay so with that said I think that is going to do it for this video hopefully now you have a good idea of how you can deploy your flask application to your own Linux server like I said before this option takes a little more effort than some of the other options out there but having your own virtual private server gives you so much more flexibility and room to grow with your application and it also provides some terrific knowledge for learning more about back in at Linux systems and that's something that you know employers really look for nowadays and something that would really shine on a resume but if you have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoyed these tutorials and would like to support them then there are several ways you can do that the easiest ways to simply like the video and give it a thumbs up also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching you

---
*Источник: https://ekstraktznaniy.ru/video/12036*