Skip to content
Advertisement

Running flask app automatically after boot does not work correctly

I am setting up Flask project in Raspberry Pi (python 2.7). It runs perfectly when the python script is called manually.

However, I am trying to run the script automatically after boot, it cannot run properly.

I have tried modifying /etc/profile to run the script after boot;

/etc/profile

# at the end of the profile
#TRIED sudo python /home/pi/project/script.py &
#TRIED sleep 10;sudo python /home/pi/project/script.py &

sudo python /home/pi/project/start_script.py &  # it also fails

start_script.py

import os
import time

time.sleep(10)
os.system('sudo python /home/pi/project/script.py &')

I expect running the server without any problem but after boot, it gives me following error,

socket.error: [Errno 98] Address already in use

However, it does not make sense as this should only happen once.

Am I missing anything here?

Advertisement

Answer

I would suggest creating a service for your app, it’s not as painful as you would think. This will start after the network is up so you don’t need an intermediate script that adds delays. There are other parameters you can add to this file if you don’t want to run as root user (the default), or you want to use virtualenv.

Create the following file /etc/systemd/system/my_project.service:

[Unit]
Description=My Project
After=network.target

[Service]
WorkingDirectory=/home/pi/project/
ExecStart=/usr/bin/python /home/pi/project/script.py
Restart=always

[Install]
WantedBy=multi-user.target

Then you can run:

sudo systemctl start my_project    
sudo systemctl status my_project

If bad, tweak and try:

sudo systemctl restart my_project
sudo systemctl status my_project

If Good:

sudo systemctl enable my_project

Reboot your pi and verify it all works.

Also double check any ports that you are using with other stuff running on the system.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement