[All-in-One]Deploy Python Flask App to AWS EC2
0. Build the python flask app locally
2. Connect EC2 with SSH automatically
First, connect EC2 with SSH:
Then, automagical the connect process:
3. Upload python files to EC2
Open the Mac terminal, and paste the following code to upload local python files exclude the venv
folder. (NOTE: when upload local file, don’t login the AWS EC2 by SSH. otherwise it will error.)
rsync -av \
--exclude='.git/' \
--exclude='.DS_Store' \
--exclude='venv_winjob' \
--exclude='__pycache__' \
--exclude='.gitattributes' \
--exclude='.gitignore' \
-e "ssh -i /Users/henrywu/MyDrive/98_Products/config/AWS_EC2_key_pair_winjob.pem" \
/Users/henrywu/MyDrive/99_Coding/01-Github/winjob/ \
ec2-user@ec2-54-185-22-17.us-west-2.compute.amazonaws.com:/home/ec2-user/winjob/
4. Set up a virtual environment of EC2
After upload the python file to EC2, we can set up virtual environment by requirements.txt.
python3 -m venv ~/winjob/venv_winjob
source ~/winjob/venv_winjob/bin/activate
pip install -r ~/winjob/requirements.txt
5. Set up a secrete manager of EC2 (optional)
Since my python flask app needs to use Openai API, and it is unsafe to save the key in the server, the best way is to use Secrets Manager of AWS.
After add the IAM role to the instance, the app can call the key safely.
6. Set up nginx to launch the web
Now we can set up Nginx to serve the Flask app on the AWS EC2, so that everyone can visit it by IP address.