场景
最近某客户有个要求,所有部署的不准运行在root下面,安装在/home/somebody下面(用户家目录),当对nginx进行普通用户运行的时候,会遇到各种各样的问题,比如文件路径不存在呀,权限不够呀等。
本文就是在修改nginx运行在家目录的时候遇到的最后一个问题,提示 useradd没有权限,以及运行的时候出现的异常现象。
$ ./nginx restart
ngx_http_fastdfs_set pid=5550
nginx: the configuration file /home/123/opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /home/123/opt/nginx/conf/nginx.conf test is successful
Stopping nginx: [ OK ]
grep: unrecognized option '--prefix=/home/123/opt/nginx'
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
./nginx: line 34: /usr/sbin/useradd: Permission denied
Starting nginx: ngx_http_fastdfs_set pid=5582
[ OK ]
touch: cannot touch `/home/123/opt/var/lock/subsys/nginx': No such file or directory
调查
- 定位代码到如下函数
make_dirs() {
# make required directories
user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\
1/g' -`
if [ -z "`grep $user /etc/passwd`" ]; then
useradd -M -s /bin/nologin $user
fi
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs //调用函数
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
可以看出,make_dirs会完成两个作用,一个是判断编译的时候的--user,如果系统中没有这个账户,那么就新建这个账户;另外一个是从options中提取temp-path变量,并创建该目录。对于我们当前的需求是不需要的,账户已经创建好了,temp-path没有,所以可以在start函数中,直接注释掉对make_dirs的调用。