Create a file for service your-service

touch /etc/systemd/system/your-service.service 

Let’s assume you want to run docker container there. Put following text in the file:

ExecStartPre=-/usr/bin/docker stop %n                                                                                                                                                                                                         
ExecStartPre=-/usr/bin/docker rm %n                                                                                                                                                                                                           
ExecStart=/usr/bin/docker run -d -p 8080:8080/tcp --name %n your_docker_image

Here we first stop and delete the docker container. If it doesn’t exist we continue (there is a “-” in before the command).


systemctl enable your-service 


# prints the status
systemctl status your-service.service  

# prepares the service, required before "start", 
# also reloads the config if you changed the definition file  
systemctl enable levels_tracker.service 

# start service
systemctl start levels_tracker.service 

# stop service
systemctl stop levels_tracker.service 


Specify working directory


Running python script from virtual environment

Just specify python interpreter from the environment:

ExecStart=<absolute path to your environment>/bin/python

Environment variables

You can set environment variables that are used for your process


Now you can use it in the ExecStart command for example:

ExecStart=<absolute path to your environment>/bin/python ${VARIABLE}

How to stdout of python-based service in syslog

Python buffers stdout. Therefore even if you have enable redirection of stdout to the syslog:


You may see nothing in the logs. You should set environment variable for python PYTHONUNBUFFERED to see the results immediately:

#in your service file add to [Service] section:

source: [here]

Probably better approach when you are allowed to install modules:

See also:

[1] stack overflow question

[2] How To Use Systemctl to Manage Systemd Services and Units

[3] How to set up proper start/stop services

[4] - great tutorial about how to set up systemd services. It also shows how to run a user services instead of system service. That requires less root privileges.