1

I'm trying to get a Flask + SocketIO app running as a service on Ubuntu 16.04, inside a virtual environment. My server is restarted every day at 3 am (outside of my control), so I need it to automatically launch on startup.

Running the script by itself works fine:

$ python main.py
(29539) wsgi starting up on http://127.0.0.1:8081

I can tell that it's working because it's serving pages (through an nginx server set up by following this Stack Overflow answer, though I don't think that's relevant.)

Here's my /etc/systemd/system/opendc.service:

[Unit]
Description=OpenDC flask + socketio service

[Service]
Environment=PYTHON_HOME=/var/www/opendc.ewi.tudelft.nl/web-server/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py
Restart=always

[Install]
WantedBy=multi-user.target

So when I try to get that going using:

$ sudo systemctl daemon-reload
$ sudo systemctl restart opendc

It doesn't serve pages anymore. The status shows:

$ sudo systemctl status opendc
* opendc.service - OpenDC flask + socketio service
   Loaded: loaded (/etc/systemd/system/opendc.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since Fri 2016-08-19 10:48:31 CEST; 15min ago
  Process: 29533 ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py (code=exited, status=203/EXEC)
 Main PID: 29533 (code=exited, status=203/EXEC)

Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Service hold-off time over, scheduling restart.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Stopped OpenDC flask + socketio service.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Start request repeated too quickly.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Failed to start OpenDC flask + socketio service.

I've looked up (code=exited, status=203/EXEC) and done some troubleshooting with what I found:

I checked that main.py is executable:

$ ls -l main.py
-rwxr-xr-x 1 leon leon 2007 Aug 19 10:46 main.py

And that main.py has this first line to point to Python in the virtual environment:

#!/var/www/opendc.ewi.tudelft.nl/web-server/venv/bin/python

So what's the problem here?

Community
  • 1
  • 1
Leon Overweel
  • 1,488
  • 4
  • 17
  • 27

2 Answers2

5

Tried and tested way of making a python file run in a Virtual Environment as a service.

[Unit][Unit]
Description=Your own description
After=network.target

[Service]
Type=simple
Restart=always
WorkingDirectory=/home/path/to/WorkingDirectory/
VIRTUAL_ENV=/home/path/to/WorkingDirectory/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/home/path/to/WorkingDirectory/venv/bin/python app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

I am putting this one here so I can always come back to it

John Kitonyo
  • 2,109
  • 1
  • 14
  • 17
0

I believe that you mistype PYTHON_HOME and than PATH=$VIRTUAL_ENV/bin:$PATH

you should use PATH=$PYTHON_HOME/bin:$PATH