title: Run Python program as service on Ubuntu 16.04 inside a virtual environment
body: <p>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.</p>
  
  <p>Running the script by itself works fine:</p>
  
  <pre><code>$ python main.py
  (29539) wsgi starting up on http://127.0.0.1:8081
  </code></pre>
  
  <p>I can tell that it's working because it's serving pages (through an nginx server set up by following <a href="https://stackoverflow.com/a/23431713/1814949">this Stack Overflow answer</a>, though I don't think that's relevant.)</p>
  
  <p>Here's my <code>/etc/systemd/system/opendc.service</code>:</p>
  
  <pre><code>[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
  </code></pre>
  
  <p>So when I try to get that going using:</p>
  
  <pre><code>$ sudo systemctl daemon-reload
  $ sudo systemctl restart opendc
  </code></pre>
  
  <p>It doesn't serve pages anymore. The status shows:</p>
  
  <pre><code>$ 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.
  </code></pre>
  
  <p>I've looked up <code>(code=exited, status=203/EXEC)</code> and done some troubleshooting with what I found:</p>
  
  <p>I checked that <code>main.py</code> is executable:</p>
  
  <pre><code>$ ls -l main.py
  -rwxr-xr-x 1 leon leon 2007 Aug 19 10:46 main.py
  </code></pre>
  
  <p>And that <code>main.py</code> has this first line to point to Python in the virtual environment:</p>
  
  <pre><code>#!/var/www/opendc.ewi.tudelft.nl/web-server/venv/bin/python
  </code></pre>
  
  <p>So what's the problem here?</p>