Lnmp multi-user Dynamic Process Management virtual host Solution

Source: Internet
Author: User
Tags stop script

A.
Features

1. high efficiency and low memory usage.
2. Permission separation. users do not interfere with each other.
3. Dynamic Process Management and balanced resource allocation.

B.
Application description

Nginx: an event-driven Web server. It adopts a modular design and is small and efficient.
PHP-FPM: supports the PHP FastCGI interface version of rapid process management, use it to achieve dynamic process management, improve resource efficiency.

C.
Brief description of the entire architecture

Nginx processes all Web requests. It matches PHP requests and sends them to the upstream server for processing. The upstream server here is PHP-CGI.
The PHP-CGI works in FastCGI mode and it listens to an address port (or a UNIX socket file, it is recommended to combine permissions to use UNIX socket more secure ), nginx will connect and send requests and reclaim results and send them to the client's browser.
Nginx runs in the WWW-data user environment, which requires that www-data users have the permission to access the Home Directory of All VM users. Each virtual host has its own PHP-CGI process group, which is dynamically managed by the PHP-FPM and is allocated evenly to resources based on increased load and reduced worker processes.
Nginx uses HTTP
The ownermatch module enables it to control which users have access to files in each location of each virtual host. About this module

D.
Configuration example of ubuntu 10.04 System

1. Install the application

sudo apt-get install nginx mysql-server php5-fpm php5-mysql

PS: it is recommended to download the patch version of nginx => https://heiher.info/1755.html
PS: Ubuntu 10.04 amd64 php5-fpm download => http://heiher.info/sftp/php5/

2. Configure nginx
Specify the number of users and workers for nginx, and make other adjustments based on actual needs.

sudo vim /etc/nginx/nginx.conf
User www-data; # specify to use www-data to execute nginxworker_processes 2; # specify 2 sub-worker Processes

3. Configure VM users
A. Create a user directory

sudo mkdir -p /var/web/USERNAME/{config,cert,run}

B. Create users and groups
This solution uses SFTP as the user's file manager, and the VM user has no terminal. For the SFTP solution, see my other log.

sudo useradd -m -g sftp -s /bin/false USERNAMEsudo mkdir -p /home/USERNAME/web/{www,logs}sudo ln -s /home/USERNAME /var/web/USERNAME/home

C. VM configuration file template
/Var/web/username/config/vhost is the virtual host configuration file, which is soft-linked to the/etc/nginx/sites-enabled/directory. Modify the username and SERVER_NAME values in the template.

# Vhost # heiher <admin@heiher.info> # HTTP serverserver {Listen 80; # Listen for IPv4 SERVER_NAME localhost; access_log/var/web/username/home/web/logs/access. log; error_log/var/web/username/home/web/logs/error. log; Location/{root/var/web/username/home/web/WWW; index index.html index.htm index. PHP; ## rewriteif (! -E $ request_filename) {rewrite ^ (. +) $/index. php? Q = $1 last;} omallow username SFTP; # allow access to the omdeny all file affiliated to Username: SFTP; # prohibit access to all other files} # pass the PHP scripts to FastCGI server listening on socket file # location ~ \. Php $ {If (! -E $ request_filename) {return 404;} fastcgi_pass Unix:/var/web/username/run/pfw. sock; fastcgi_index index. PHP; fastcgi_param script_filename/var/web/username/home/web/www/$ fastcgi_script_name; Include fastcgi_params;} # deny access. htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\. HT {deny all ;}# HTTPS serverserver {Listen 443; ## listen for IPv4 SERVER_NAME localhost; SSL on; ssl_certificate/var/web/username/CERT/cert. PEM; ssl_certificate_key/var/web/username/CERT/cert. key; ssl_session_timeout 5 m; ssl_protocols SSLv3 tlsv1; ssl_ciphers all :! ADH :! Export56: RC4 + RSA: + high: + medium: + low: + SSLv3: + exp; ssl_prefer_server_ciphers on; access_log/var/web/username/home/web/logs/access. log; error_log/var/web/username/home/web/logs/error. log; Location/{root/var/web/username/home/web/WWW; index index.html index.htm index. PHP; ## rewriteif (! -E $ request_filename) {rewrite ^ (. +) $/index. php? Q = $1 last;} omallow username SFTP; omdeny all;} # pass the PHP scripts to FastCGI server listening on socket file # location ~ \. Php $ {If (! -E $ request_filename) {return 404;} fastcgi_pass Unix:/var/web/username/run/pfw. sock; fastcgi_index index. PHP; fastcgi_param script_filename/var/web/username/home/web/www/$ fastcgi_script_name; fastcgi_param HTTPS on; Include fastcgi_params;} # deny access. htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\. Ht {deny all ;}}

D. PHP-FPM pool profile template
/Var/web/username/config/php5-fpm.conf is the PHP-FPM pool configuration file and soft links to the/etc/PhP5/FPM/pool. d/directory. Modify the username in the template. You can adjust the dynamic process management parameters as needed.

; Start a new pool name[USERNAME] ; The address on which to accept FastCGI requests.; Valid syntaxes are:;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on;                            a specific port;;   'port'                 - to listen on a TCP socket to all addresses on a;                            specific port;;   '/path/to/unix/socket' - to listen on a unix socket.; Note: This value is mandatory.listen = /var/web/USERNAME/run/pfw.sock ; Set listen(2) backlog. A value of '-1' means unlimited.; Default Value: -1;listen.backlog = -1 ; List of ipv4 addresses of FastCGI clients which are allowed to connect.; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address; must be separated by a comma. If this value is left blank, connections will be; accepted from any ip address.; Default Value: any;listen.allowed_clients = 127.0.0.1 ; Set permissions for unix socket, if one is used. In Linux, read/write; permissions must be set in order to allow connections from a web server. Many; BSD-derived systems allow connections regardless of permissions. ; Default Values: user and group are set as the running user;                 mode is set to 0666listen.owner = USERNAMElisten.group = www-datalisten.mode = 0660 ; Unix user/group of processes; Note: The user is mandatory. If the group is not set, the default user's group;       will be used.user = USERNAMEgroup = sftp ; Choose how the process manager will control the number of child processes.; Possible Values:;   static  - a fixed number (pm.max_children) of child processes;;   dynamic - the number of child processes are set dynamically based on the;             following directives:;             pm.max_children      - the maximum number of children that can;                                    be alive at the same time.;             pm.start_servers     - the number of children created on startup.;             pm.min_spare_servers - the minimum number of children in 'idle';                                    state (waiting to process). If the number;                                    of 'idle' processes is less than this;                                    number then some children will be created.;             pm.max_spare_servers - the maximum number of children in 'idle';                                    state (waiting to process). If the number;                                    of 'idle' processes is greater than this;                                    number then some children will be killed.; Note: This value is mandatory.pm = dynamic ; The number of child processes to be created when pm is set to 'static' and the; maximum number of child processes to be created when pm is set to 'dynamic'.; This value sets the limit on the number of simultaneous requests that will be; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP; CGI.; Note: Used when pm is set to either 'static' or 'dynamic'; Note: This value is mandatory.pm.max_children = 10 ; The number of child processes created on startup.; Note: Used only when pm is set to 'dynamic'; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2pm.start_servers = 3 ; The desired minimum number of idle server processes.; Note: Used only when pm is set to 'dynamic'; Note: Mandatory when pm is set to 'dynamic'pm.min_spare_servers = 2 ; The desired maximum number of idle server processes.; Note: Used only when pm is set to 'dynamic'; Note: Mandatory when pm is set to 'dynamic'pm.max_spare_servers = 8 ; The number of requests each child process should execute before respawning.; This can be useful to work around memory leaks in 3rd party libraries. For; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.; Default Value: 0pm.max_requests = 8192 ; The URI to view the FPM status page. If this value is not set, no URI will be; recognized as a status page. By default, the status page shows the following; information:;   accepted conn    - the number of request accepted by the pool;;   pool             - the name of the pool;;   process manager  - static or dynamic;;   idle processes   - the number of idle processes;;   active processes - the number of active processes;;   total processes  - the number of idle + active processes.; The values of 'idle processes', 'active processes' and 'total processes' are; updated each second. The value of 'accepted conn' is updated in real time.; Example output:;   accepted conn:   12073;   pool:             www;   process manager:  static;   idle processes:   35;   active processes: 65;   total processes:  100; By default the status page output is formatted as text/plain. Passing either; 'html' or 'json' as a query string will return the corresponding output; syntax. Example:;   http://www.foo.bar/status;   http://www.foo.bar/status?json;   http://www.foo.bar/status?html; Note: The value must start with a leading slash (/). The value can be;       anything, but it may not be a good idea to use the .php extension or it;       may conflict with a real PHP file.; Default Value: not set ;pm.status_path = /status ; The ping URI to call the monitoring page of FPM. If this value is not set, no; URI will be recognized as a ping page. This could be used to test from outside; that FPM is alive and responding, or to; - create a graph of FPM availability (rrd or such);; - remove a server from a group if it is not responding (load balancing);; - trigger alerts for the operating team (24/7).; Note: The value must start with a leading slash (/). The value can be;       anything, but it may not be a good idea to use the .php extension or it;       may conflict with a real PHP file.; Default Value: not set;ping.path = /ping ; This directive may be used to customize the response of a ping request. The; response is formatted as text/plain with a 200 response code.; Default Value: pong;ping.response = pong ; The timeout for serving a single request after which the worker process will; be killed. This option should be used when the 'max_execution_time' ini option; does not stop script execution for some reason. A value of '0' means 'off'.; Available units: s(econds)(default), m(inutes), h(ours), or d(ays); Default Value: 0;request_terminate_timeout = 0 ; The timeout for serving a single request after which a PHP backtrace will be; dumped to the 'slowlog' file. A value of '0s' means 'off'.; Available units: s(econds)(default), m(inutes), h(ours), or d(ays); Default Value: 0;request_slowlog_timeout = 0 ; The log file for slow requests; Default Value: /var/log/php-fpm.log.slow;slowlog = /var/log/php-fpm.log.slow ; Set open file descriptor rlimit.; Default Value: system defined value;rlimit_files = 1024 ; Set max core size rlimit.; Possible Values: 'unlimited' or an integer greater or equal to 0; Default Value: system defined value;rlimit_core = 0 ; Chroot to this directory at the start. This value must be defined as an; absolute path. When this value is not set, chroot is not used.; Note: chrooting is a great security feature and should be used whenever ;       possible. However, all PHP paths will be relative to the chroot;       (error_log, sessions.save_path, ...).; Default Value: not set;chroot =  ; Chdir to this directory at the start. This value must be an absolute path.; Default Value: current directory or / when chrootchdir = /var/web/USERNAME/home/web/www ; Redirect worker stdout and stderr into main error log. If not set, stdout and; stderr will be redirected to /dev/null according to FastCGI specs.; Default Value: no;catch_workers_output = yes ; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from; the current environment.; Default Value: clean env;env[HOSTNAME] = $HOSTNAME;env[PATH] = /usr/local/bin:/usr/bin:/bin;env[TMP] = /tmp;env[TMPDIR] = /tmp;env[TEMP] = /tmp ; Additional php.ini defines, specific to this pool of workers. These settings; overwrite the values previously defined in the php.ini. The directives are the; same as the PHP SAPI:;   php_value/php_flag             - you can set classic ini defines which can;                                    be overwritten from PHP call 'ini_set'. ;   php_admin_value/php_admin_flag - these directives won't be overwritten by;                                     PHP call 'ini_set'; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no. ; Defining 'extension' will load the corresponding shared extension from; extension_dir. Defining 'disable_functions' or 'disable_classes' will not; overwrite previously defined php.ini values, but will append the new value; instead. ; Default Value: nothing is defined by default except the values in php.ini and;                specified at startup with the -d argument;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com;php_flag[display_errors] = off;php_admin_value[error_log] = /var/log/fpm-php.www.log;php_admin_flag[log_errors] = on;php_admin_value[memory_limit] = 32M

E. Set Directory Permissions
This step is critical and must be carefully set. Do not modify it unless otherwise required. If I am wrong, thank you for your correction.

Sudo chown-r root: root/var/web/username/configsudo chmod 0755/var/web/username/configsudo chmod 0640/var/web/username/cofnig/vhostsudo chmod 0640/var/web/username/ config/php5-fpm.conf sudo chown-r www-data: WWW-data/var/web/username/certsudo chmod 0750/var/web/username/certsudo chmod 0640/var/web/username/CERT/cert. pemsudo chmod 0640/var/web/username/CERT/cert. key sudo chown Username: www-d ATA/var/web/username/runsudo chmod 0750/var/web/username/run sudo chown root: Root/home/usernamesudo chown-r username: WWW-data/home/username/websudo chmod 0755/home/usernamesudo chmod 0750/home/username/Web # Note: all files and directories in the/home/username/web/WWW directory must belong to Username: SFTP, And the File Permission is 0644, And the directory permission is 0755.

F. Enable this user's virtual host and PHP

Sudo ln-S/var/web/username/config/vhost/etc/nginx/sites-enabled/usernamesudo ln-S/var/web/username/config/php5-fpm.conf/etc/ phP5/FPM/pool. d/username. confsudo nginx-T # test the script before restart whether there is an error in sudo service nginx reloadsudo service php5-fpm restart

PS: all virtual users belong to the SFTP user group. In this solution, SFTP is recommended as your file transfer window. In sshd_config, impose necessary restrictions on SFTP group users, such as forwarding prohibition and chroot.

Over!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.