我有以下单元文件:
[Unit]
Description=Panel for Systemd Services
After=network.target
[Service]
User=pysd
Group=pysd
PermissionsStartOnly=true
WorkingDirectory=/opt/pysd
ExecStartPre=/bin/mkdir /run/pysd
ExecStartPre=/bin/chown -R pysd:pysd /run/pysd
ExecStart=/usr/local/bin/gunicorn app:app -b 127.0.0.1:8100 --pid /run/pysd/pysd.pid --workers=2
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
ExecStopPost=/bin/rm -rf /run/pysd
PIDFile=/run/pysd/pysd.pid
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Alias=pysd.service我想用ExecStartPre创建一个环境变量,然后将这个变量合并到ExecStart中。
具体来说,我想在运行GUNICORN_SERVER之前创建一个环境变量ExecStart,然后在ExecStart上为选项-b使用这个环境变量。
我尝试了类似于ExecStartPre=/bin/bash -c 'export GUNICORN_SERVER=127.0.0.1:8100'的东西,但是没有创建任何环境变量。
我如何实现这个场景?
发布于 2019-04-11 04:47:36
您不能使用ExecStartPre直接为其他ExecStartPre或ExecStart命令设置环境--这些都是单独的进程。(当然,通过将文件保存到文件并读取它或其他什么东西,可以间接地实现。)
Systemd有两种设置环境的方法:Environment=和EnvironmentFile=。在man 5 systemd.exec中都有这两个方面的例子。这些影响到服务启动的所有进程,包括用于ExecStartPre的进程。如果不需要动态设置这些变量,那么这是一个很好的选择:
Environment=GUNICORN_SERVER=127.0.0.1:8080但是,如果您需要动态地设置变量,则手册说明了EnvironmentFile的如下内容:
The files listed with this directive will be read shortly before the process is
executed (more specifically, after all processes from a previous unit state
terminated. This means you can generate these files in one unit state, and read it
with this option in the next).因此,一种选择是将其写入ExecStartPre中的文件,并让systemd将该文件作为EnvironmentFile的一部分读取:
EnvironmentFile=/some/env/file
ExecStartPre=/bin/bash -c 'echo foo=bar > /some/env/file'
ExecStart=/some/command # sees bar as value of $foo另一种选择是在ExecStart中使用shell:
ExecStart=/bin/sh -c 'export GUNICORN_SERVER=127.0.0.1:8080; exec /usr/local/bin/gunicorn ...'发布于 2019-04-18 07:25:34
实际上,最好的方法是使用Gunicorn的--env,它在操作系统上创建一个环境变量,您可以读取该变量并将数据合并到您的Python应用程序中:
在你的单位档案上:
ExecStart=/usr/local/bin/gunicorn app:app -b 127.0.0.1:8100 --env GUNICORN_SERVER="127.0.0.1:8100" --pid /run/pysd/pysd.pid --workers=2在您的应用程序中(例如,烧瓶):
import os
from flask import Flask
app = Flask(__name__)
gs = os.getenv('GUNICORN_SERVER')
if gs:
app.config["SERVER_NAME"] = gs
else:
app.config["SERVER_NAME"] = "127.0.0.1:8100"谢谢你的评论,JdeBP。事实上,文档有很多信息。
https://unix.stackexchange.com/questions/511797
复制相似问题