description "myapp node.js server" start on runlevel [2345] stop on shutdown env NODE_ENV=production env CUSTOM=somevalue exec sudo -u nodejs /usr/local/bin/node /opt/myapp/app.js >> /var/log/nodejs/myapp.log 2>&1 post-start script NODE_PID=`status myapp | egrep -oi '([0-9]+)$' | head -n1` echo $NODE_PID > /var/run/nodejs/myapp.pid end script
但是,应用程序看不到NODE_ENV设置为生产。事实上,如果我在应用程序内的console.log(process.env),我没有看到NODE_ENV或CUSTOM。任何想法发生了什么?
顺便说一下,NODE_ENV =生产节点app.js工作正常。
解决方法
There are two distinct ways to deal with environment variables. By default,the env_reset sudoers
option is enabled. This causes commands to be executed with a minimal environment containing TERM,
PATH,HOME,SHELL,LOGNAME,USER and USERNAME in addition to variables from the invoking process
permitted by the env_check and env_keep sudoers options. There is effectively a whitelist for
environment variables.
Sudo正在重置环境。这是一个令人沮丧的方面在upstart或init脚本中使用su和sudo。最新版本的upstart支持在不使用sudo的情况下通过setuid / setgid指令指定uid / gid,如下面的示例所示。还要注意使用chdir。
start on filesystem and started networking respawn chdir /var/www/yourapp setuid yourapp setgid yourapp env NODE_ENV=production env PATH=/usr/local/bin:/usr/bin:/bin env CUSTOM=somevalue exec /usr/local/bin/node app.js | /usr/bin/multilog s1024000 /var/log/yourapp 2>&1
对于较旧版本的upstart,这里是我习惯做的工作。
description "start and stop the example.com node.js server" start on filesystem and started networking respawn chdir /path/to/your/code exec su -c 'PATH=$PWD/node/bin NODE_ENV=$(cat node_env.txt) ./node/bin/node app/server.js' www-data >> tmp/stdout.log 2>&1
注意,我只是把一个node_env.txt文件在我的应用程序根设置生产模式,因为I hate environment variables.你可以只做NODE_ENV =生产在那里如果你喜欢。