0

The design pattern for spawning web server workers seems to be that they are started by root in an init script and then spawn a process as an unprivileged user. For example, I start a gunicorn web server daemon in an init script like this:

#!/bin/sh

$LOGFILE=/var/log/gunicorn.error.log
$PIDFILE=/var/run/gunicorn.pid

[...]
gunicorn -u nobody -b 127.0.0.1:8000 \
    --error-logfile=$LOGFILE --pidfile=$PIDFILE -D

I can spawn my own scripts as an unprivileged user (see this question), but that process can no longer write log files to /var/log.

How do I enable a worker spawned by a root process to write log files to /var/log and PID files to /var/run?

Community
  • 1
  • 1
user545424
  • 15,713
  • 11
  • 56
  • 70

1 Answers1

2

By creating a folder for your process inside the /var/log and /var/run folders, you can change the owner and group from within the init script (as it's ran by root), so the process will have write access to it. For /var/log, it is enough to create the folder once, but the /var/run folder will have to be recreated on every system restart. This is how I solved it (for simplicity I recreate here both folders):

DAEMON_USER='unprivilegeduser'
DAEMON_GROUP='unprivilegedgroup'
DAEMON_PID_DIR='/var/run/myprocessname'
DAEMON_LOG_DIR='/var/log/myprocessname'
PIDFILE="$DAEMON_PID_DIR/gunicorn.pid"
LOGFILE="$DAEMON_LOG_DIR/gunicorn.error.log"

mkdir -p $DAEMON_PID_DIR
mkdir -p $DAEMON_LOG_DIR
chown $DAEMON_USER:$DAEMON_GROUP $DAEMON_PID_DIR
chown $DAEMON_USER:$DAEMON_GROUP $DAEMON_LOG_DIR

[...]
gunicorn -u nobody -b 127.0.0.1:8000 \
    --error-logfile=$LOGFILE --pidfile=$PIDFILE -D
andrean
  • 6,717
  • 2
  • 36
  • 43