Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An example network service with systemd-activated socket in Python. #systemd #python #socket #socket-activation


The example below creates a TCP server listening on a stream (i.e. SOCK_STREAM) socket. A similar approach can be followed to create a UDP server on a datagram (i.e. SOCK_DGRAM) socket. See man systemd.socket for details.

An example server

Create an simple echo server at /opt/foo/


from SocketServer import TCPServer, StreamRequestHandler
import socket
import logging

class Handler(StreamRequestHandler):
    def handle(self): = self.rfile.readline().strip()"From <%s>: %s" % (self.client_address,
        self.wfile.write( + "\r\n")

class Server(TCPServer):
    # The constant would be better initialized by a systemd module

    def __init__(self, server_address, handler_cls):
        # Invoke base but omit bind/listen steps (performed by systemd activation!)
            self, server_address, handler_cls, bind_and_activate=False)
        # Override socket
        self.socket = socket.fromfd(
            self.SYSTEMD_FIRST_SOCKET_FD, self.address_family, self.socket_type)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999 # not really needed here
    server = Server((HOST, PORT), Handler)

Define the systemd service unit

Create the service definition unit file at /etc/systemd/system/foo.service (note that this unit refers to foo.socket):

Description=Foo Service foo.socket

ExecStart=/usr/bin/python /opt/foo/


Define the systemd socket unit

Create the socket definition unit file at /etc/systemd/system/foo.socket:

Description=Foo Socket



Test it

Send a message to the listening service:

echo "Hello World"| netcat 9999

This comment has been minimized.

Copy link

commented Sep 3, 2016

Thanks for writing this up! It saved me alot of time experimenting with some socket activation stuff. For those interested, my fork adds python3 support and uses the systemd user daemon.


This comment has been minimized.

Copy link

commented Nov 27, 2018

This is very useful thanks for sharing.

Are there any throttling limits on this imposed say by python or something?

If I open it up (by changing --> and have a syslog-ng server streaming on this listener, could there (in theory) be any logs lost due to the rate that syslog-ng serves data?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.