如何使用 systemd 服务或 tmpfiles.d 自动创建运行时文件夹?

geo*_*aut 12 ubuntu python systemd socket

我正在尝试/run/gunicorn为一些 Gunicorn 套接字/PID 文件创建一个运行时文件夹,这些文件用于 Django 应用程序。如果我手动创建目录,我可以让一切正常。但是,我正在尝试使其成为一个健壮的设置,并最终使用 Ansible 来自动化一切。

我想我有 2 个选项,基于这个问题

选项 1 - 运行时目录

我认为第一个选项是RuntimeDirectory=在我的 systemd 服务文件中使用,但我无法使用它来创建文件夹。服务文件包含:

#/etc/systemd/system/gunicorn_django_test.service
[Unit]
Description=gunicorn_django daemon
After=network.target

[Service]
User=gunicorn
Group=www-data
RuntimeDirectory=gunicorn #This line is supposed to create a directory
RuntimeDirectoryMode=755
PIDFile=/run/gunicorn/django_test_pid
WorkingDirectory=/vagrant/webapps/django_venv/django_test
ExecStart=/vagrant/webapps/django_venv/bin/gunicorn --pid /run/gunicorn/django_test_pid --workers 3 --bind unix:/run/gunicorn/django_test_socket django_test.wsgi --error-logfile /var/log/gunicorn/django_test_error.log
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

当我运行时systemctl start gunicorn_django_test.service,服务无法启动。当我剪掉 exec 行并手动运行它时,我得到Error: /run/gunicorn doesn't exist. Can't create pidfile.如果我/run/gunicorn手动创建文件夹,我可以让事情工作。

选项 2 - tmpfiles.d

第二个选项是用于tmpfiles.d在启动时创建一个文件夹,为 pid/socket 文件做好准备。我试过这个文件:

#/etc/tmpfiles.d/gunicorn.conf
d /run/gunicorn 0755 gunicorn www-data -
Run Code Online (Sandbox Code Playgroud)

这将创建一个目录,但它以某种方式很快被删除,当我启动服务时,该文件夹不可用。

我可以手动将一些 PreExecmkdir命令添加到服务文件中,但我想了解为什么 RuntimeDirectory / tmpfiles.d 不起作用。谢谢。

版本/信息:Ubuntu 16.04 Server / systemd 229 / Gunicorn 19.7.1 / runtime dir = /run

geo*_*aut 13

PermissionsStartOnly=True按照建议添加并为每个服务设置了一个运行时文件夹。我还添加0了开始的文件夹模式。

[Unit]
Description=gunicorn_django daemon
After=network.target

[Service]
PermissionsStartOnly=True
User=gunicorn
Group=www-data
RuntimeDirectory=gunicorn_django
RuntimeDirectoryMode=0775
PIDFile=/run/gunicorn_django/django_test_pid
WorkingDirectory=/vagrant/webapps/django_venv/django_test
ExecStart=/vagrant/webapps/django_venv/bin/gunicorn --pid /run/gunicorn_django/django_test_pid --workers 3 --bind unix:/run/gunicorn_django/django_test_socket django_test.wsgi --error-logfile /var/log/gunicorn/django_test_error.log
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

它现在正在创建一个具有正确权限的文件夹。

drwxrwxrw-  2 gunicorn www-data   40 Mar 30 07:11 gunicorn_django/
Run Code Online (Sandbox Code Playgroud)

感谢@quixotic 和@mark-stosberg