How to convert a python script in a local conda env into systemd service in Linux?

Viewed 4941

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?

1 Answers

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.

Related