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

Corey Schafer · Beginner ·🔧 Backend Engineering ·7y ago

Key Takeaways

Deploying a Flask application to a Linux server using Linode, Nginx, and Gunicorn, covering the entire deployment process from scratch, including setting up a Linux server, configuring SSH, installing dependencies, and exposing the application to the outside world.

Full Transcript

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 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 how to deploy to 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 Apache and mod whiskey 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 going to click on 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 gonna add a root password 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 I'm going to use to run commands on 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 to set the host equal to 0 0 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 to create a new user 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 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 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 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 so this is going to be 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 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 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 incogn

Original Description

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
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Corey Schafer · Corey Schafer · 0 of 60

← Previous Next →
1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
19 JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
39 Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
40 Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
47 Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This video tutorial covers the deployment of a Flask application to a Linux server using Linode, Nginx, and Gunicorn. It covers the entire deployment process from scratch, including setting up a Linux server, configuring SSH, installing dependencies, and exposing the application to the outside world.

Key Takeaways
  1. Create a new Linode server with a high-performance stateful Linux image
  2. Choose a region and Linode plan
  3. Add a root password and optional add-ons
  4. Access the server using SSH
  5. Upgrade software with apt update and apt upgrade
  6. Set hostname with hostnamectl set-hostname
  7. Edit hosts file with Nano
  8. Use Linux bash shell on Windows or Putty for SSH access
  9. Set host name in /etc/hosts file using Nano editor
  10. Add a limited user to the machine with limited privileges
💡 Deploying a Flask application to a Linux server requires careful configuration of SSH, firewall rules, and server settings to ensure secure and efficient deployment.

Related Reads

📰
I built a native Android app in an afternoon, and I've never written a line of Kotlin
Learn how to build a native Android app without prior Kotlin knowledge, leveraging modern tools and frameworks to streamline development
Dev.to · Tilde A. Thurium
📰
Vibe Coding Is Real Now — Here’s How to Do It Without Wrecking Your Codebase
Learn how to apply vibe coding effectively to speed up feature development without compromising code quality, and why discipline is key to its success
Medium · Programming
📰
How to build your first MCP server in 10 minutes
Learn to build a Minecraft server using MCP in under 10 minutes for a seamless gaming experience
Dev.to · GrahamduesCN
📰
Revisiting My Software Engineering Journey
Learn how browsers communicate with servers using HTTP and HTTPS protocols, essential for software engineers to build scalable web applications
Medium · JavaScript
Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →