How to Deploy Flas App on AWS

May 9, 2024

Owner: milan
Tags: Guides and Processes

How to Deploy Flask App on AWS

đź“– Summary

đź’ˇ Use this guide to, how our server is running and all the key function to deploy on the server

1. How to access EC2-AWS instance

  • Go inside the folder where .pem file in your computer, .pem is file for authorization to access your aws instance.

  • Then run the following command

  • Then you can follow the process of accessing instance through SSH as mentioned below

    SSH Access:

2. Accessing source code inside remote instance

  • To access the source code, first authorization your GitHub.com with your EC2 instance.

    • Best way to do this is to create a new SSH key on your EC2 instance and add it to your GitHub account.

    • To create a new SSH key, run the following command on your EC2 instance:

      ssh-keygen -t rsa -b 4096 -C "
      
    • When you’re prompted to “Enter a file in which to save the key,” press Enter. This accepts the default file location.

    • At the prompt, type a secure passphrase. This will add an extra layer of security to your SSH key.

    • To display the SSH key, run the following command:

      cat ~/.ssh/id_rsa.pub
    • Copy the SSH key to your clipboard.

    • Go to your GitHub account settings and click on SSH and GPG keys.

    • Click on New SSH key and paste the SSH key you copied from your EC2 instance.

    • Give the key a title and click Add SSH key.

    • Now you can clone your repository on your EC2 instance using the SSH URL.

    • To clone your repository, run the following command:

      git clone <Your github ssh clone URL>
      
    • You will be prompted to enter your passphrase. Enter the passphrase you created when you generated the SSH key.

    • You can now access your source code on your EC2 instance.

  • To create a virtual environment for your project, run the following commands:

    python3 -m venv myprojectenv
    source myprojectenv/bin/activate
  • Pull the latest code from the GitHub:

    git pull origin master

3. Creating Service file


ℹ️ Service file are those files, by which we can keep running our project without crashing it and in deployment we can run the our app without worry of crashing and process management properly

  • We are using gunicorn for process and worker management for our flask app deployment

Example of service file for flask server:

[Unit]
Description=Gunicorn instance to serve myproject
After=network.target

[Service]
User=ubuntu
Group=www-data #(optional)
WorkingDirectory=/home/ubuntu/tpndataautomation/tpncelery
Environment="PATH=/home/ubuntu/tpndataautomation/tpndataautomation/bin"
ExecStart=/home/ubuntu/tpndataautomation/tpndataautomation/bin/gunicorn --workers 5 --bind unix:tpncelery.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target
  • This service file contains the things like path to environment for the application, user of the system e.g. ubuntu, directory in which source code is lying, and command that run app with gunicorn


Please make sure that you are creating wsgi.py file for deployment server

  • wsgi.py file is the entry point for the application, where the gunicorn will start the application
from app import create_app

app = create_app()

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

To create this file please run this following command on instance

sudo nano /etc/systemd/system/<name of the service>.service
  • Than copy and path the above service file content inside the editor appear after running this command
  • Now, press cltr + x and then press y , now lets enable the service file

To enable the service file and start the service file use the following commands

#start the service file
sudo systemctl start myproject

#only run first time after creating service file
sudo systemctl enable myproject

#to check the status of the service, weather running or any error occured
sudo systemctl status myproject

#to restart the service after making any changes
sudo systemctl restart myproject

To create this file please run this following command on instance

sudo nano /etc/systemd/system/<name of the service>.service

3. Nginx server setup for proxy request

To create nginx file please do the following process

sudo nano /etc/nginx/sites-available/myproject
  • First, run the following command and change myproject with your desire name you want to give to your nginx server
server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        include proxy_params; #change this to your original URL where you want to setup proxy
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}

Save and close the file when you’re finished.

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

With the file in that directory, you can test for syntax errors:

sudo nginx -t

If this returns without indicating any issues, restart the Nginx process to read the new configuration:

sudo systemctl restart nginx

Finally, adjust the firewall again. You no longer need access through port 5000, so you can remove that rule. You can then allow full access to the Nginx server:

sudo ufw allow 'Nginx Full'

link your newly creates nginx file

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

5. Redis and celery setup

To access the redis please run the following command

redis-cli - then type ping it will return pong if everything is correct or shows the error

How to change the redis password

  • sudo nano /etc/redis/redis.conf

  • run this command you will be able to see the redis configuration file, than search for the requirepass

  • Change the password to your desire password

    requirepass your_password_here

To search inside this doc, press cltr + w and the type the string you want to search for

  • Congratulations, your redis password is now updated

  • Save the configuration file (in Nano, press Ctrl + O and then Enter to save, and Ctrl + X to exit).

  • Restart the Redis server to apply the changes:

    sudo systemctl restart redis
  • To test the password protection, try connecting to the Redis server using the redis-cli tool with the password:

    redis-cli -a your_password_here

6. How to access the Postgres database


♻️ HERE ARE THE ALL DATABASE DETAILS

Access Postgres:

host: host IP

post: 5432

Username: postgres

Password: <your password>
  • To access the Postgres database, you can use the psql command. You can connect to the database by specifying the database name and the username:
psql -d postgres -U postgres

**Important

  • Make sure that you restart the service for the flask after performing any changes to keep updated our application**