Deploy python flask app on Linux Server
After creating a Python App on your local machine you need to deploy your app on the server so that app can be accessed from anywhere. On your local environment, you run your app by using python or a python3 prompt like below.
The app will stop after you close the terminal. So for deploying the Python app on the server, you need to create a service container that will run permanently your app. We are proving steps to deploy your python app on the server.
Create a python app and upload into a directory on the server. In our example, I have created index.py file that contains entrance point of application.
sudo mkdir /var/www/mypythonapp sudo touch /var/www/mypythonapp/index.py sudo vim /var/www/mypythonapp/index.py
Install all dependencies for your app using pip. For example:
pip install python-flask
Now create a service for your app and open for edit.
sudo vim /etc/systemd/system/mypythonapp.service sudo nano /etc/systemd/system/mypythonapp.service
Now write the script in this file.
[Unit] Description=My Python App After=multi-user.target [Service] ExecStart=/usr/bin/python3 /var/www/mypythonapp/index.py Type=idle [Install] WantedBy=multi-user.target
Here /usr/bin/python3 is my python startup path and after that my python file path to start running.
If you want to store all python output in a log file then provide path od log file as below and make sure that log directory is writable.
[Unit] Description=My Python App After=multi-user.target [Service] ExecStart=/usr/bin/python3 /var/www/mypythonapp/index.py > /var/www/mypythonapp/log.txt Type=idle [Install] WantedBy=multi-user.target
Now save and close this file. - (ctrl+o then ctrl+x)
Change this service file permission to 644.
sudo chmod 644 /etc/systemd/system/mypythonapp.service
Now apply this service and enable to execute.
sudo systemctl daemon-reload sudo systemctl enable mypythonapp.service
Now start your service.
sudo systemctl start mypythonapp.service
Your app is now running.
To stop the app run following command.
sudo systemctl stop mypythonapp.service
To check the status of service run following command.
sudo systemctl status mypythonapp.service