9

I have a daemon Python script in my conda environment which I run it:

source activate my_env
python my_server.py 

I would like to convert it to as systemd service, so I created my_server.service file:

[Service]
User=myuser
Group=myuser
Type=simple
ExecStart=/home/myuser/.conda/envs/my_env/bin/python /path/to/my_server.py

This does not work because the systemd is being run as the root user and I can not activate the conda environment to get the all path right. What is the correct way to create a systemd service when the executable requires a specific conda env to run?

motam79
  • 3,542
  • 5
  • 34
  • 60

1 Answers1

13

You can run systemd services on user level instead of running on system level, which will run it as root user. Instead of putting the .service file on /etc/systemd/system directory, you have put the file inside ~/.config/systemd/user/ directory and no need of User and Group derivative. For example:

[Unit]
Description=Description
After=network.target

[Service]
Type=simple
WorkingDirectory=/path/to/
ExecStart=/home/myuser/.conda/envs/my_env/bin/python my_server.py

[Install]
WantedBy=default.target

Instead of starting this service with privileged permission, you can start with the running user permission using systemctl --user start/restart/stop servicename command. No need of sudo privilege or password.

arryph
  • 2,725
  • 10
  • 15
  • If I run it as a user, can I configure it to run at every boot automatically? – motam79 Dec 26 '18 at 07:05
  • 1
    Yes you can, for system level services `WantedBy=multiuser.target` is required for a system to be enabled, in case of user level services, `WantedBy=default.target`. For starting at boot, you have to enable-linger for that user, command is `loginctl enable-linger username`. You can just enable the service using `systemctl --user enable servicename` command. – arryph Dec 26 '18 at 07:11
  • 5
    It looks like this solution wouldn't actually activate the conda environment – which will be problematic if `my_server.py` depends on conda packages with activation scripts. – Charles Holbrow Dec 04 '19 at 02:43