Skip to content
Skip to the article
In Linux: 9 articles
Linux

Clean Up Stale nginx Unix Sockets with a systemd Drop-in

Add a systemd drop-in that removes leftover Unix socket files before nginx starts, so it doesn't fail with Address already in use.

Updated
Applies to
  • Ubuntu 24.04
  • systemd 255
  • nginx 1.24
Tags
  • nginx
  • systemd
  • ubuntu
Reading time
3 min

When nginx listens on Unix sockets (for example listen unix:/run/nginx-sockets/site.sock; behind a load balancer or another proxy), it normally removes the socket files when it shuts down cleanly. After a crash, a kill -9, or a power loss, the files stay behind, and the next start fails:

nginx: [emerg] bind() to unix:/run/nginx-sockets/site.sock failed (98: Address already in use)

A systemd drop-in can delete stale sockets every time the service starts.

Add the Drop-in

  1. Keep nginx's sockets in a directory used only by nginx, such as /run/nginx-sockets, so the cleanup can't touch another service's sockets (PHP-FPM, for example).

  2. Create the drop-in with systemctl edit, which opens an editor and saves the file to /etc/systemd/system/nginx.service.d/override.conf:

    systemctl edit nginx

    Add:

    [Service]
    ExecStartPre=/bin/sh -c 'rm -f /run/nginx-sockets/*.sock'

    Or write the file directly:

    mkdir -p /etc/systemd/system/nginx.service.d
    printf '%s\n' '[Service]' "ExecStartPre=/bin/sh -c 'rm -f /run/nginx-sockets/*.sock'" > /etc/systemd/system/nginx.service.d/rm-sock.conf
    systemctl daemon-reload
  3. Restart nginx and confirm the drop-in is loaded:

    systemctl restart nginx
    systemctl cat nginx

The command runs through /bin/sh because systemd doesn't expand wildcards like *.sock itself. Drop-in ExecStartPre lines run after the ones in the main unit, so Ubuntu's built-in nginx -t config test still runs first.

Note

Put drop-ins under /etc/systemd/system/, not /lib/systemd/system/ or /usr/lib/systemd/system/. Files in those directories belong to packages and can be overwritten on upgrade.

Alternative: Let systemd Manage the Directory

If the socket directory lives under /run, systemd can create it at start and delete it, with everything inside, at stop:

[Service]
RuntimeDirectory=nginx-sockets
RuntimeDirectoryMode=0755

systemd removes the directory whenever the service stops, including when it fails or is killed, and /run is cleared on reboot, so stale sockets can't survive. Use this or the ExecStartPre cleanup, not both: RuntimeDirectory deletes the directory on stop, so nothing else should store files in it.

Sources

This article is in the public domain (CC0 1.0), code samples included. Use it however helps you.