Pages

Monday, 24 December 2018

Install Nginx, PHP7, MariaDB10 (LEMP) on CentOS7 OR Ubuntu

yum update
yum install epel-release

Nginx

yum install nginx
systemctl start nginx
systemctl enable nginx

MariaDB 10

vi /etc/yum.repos.d/MariaDB.repo
add
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
then
yum install MariaDB-server MariaDB-client
systemctl start mariadb Y, Y, Y, Y mysql_secure_installation
systemctl enable mariadb

PHP 7

add the Webtatic repo:
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
install
yum install php70w
see if it works or not
php -v
Search available modules
yum search php70
install modules you need
yum install php70w-xml php70w-soap php70w-xmlrpc php70w-mbstring php70w-json php70w-gd php70w-mcrypt php70w-mysql 
yum install php70w-intl php70w-tidy
yum install php70w-pecl-redis 
yum install php-pecl-mongodb
yum install php70w-fpm
yum install php70w-devel php70w-pear
yum install php70w-pecl-apcu php70w-opcache
vi /etc/php.ini
find cgi.fix_pathinfo=1 and then replace it with cgi.fix_pathinfo=0
vi /etc/php-fpm.d/www.conf
find and replace with:
listen = /var/run/php-fpm/php-fpm.sock
listen.owner = nobody
listen.group = nobody
user = nginx
group = nginx
Start php-fpm
systemctl start php-fpm
Enable it to boot
systemctl enable php-fpm
vi /etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name  localhost;

    # note that these lines are originally from the "location /" block
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
If meet permission denied issue..
chown nginx:nginx /var/run/php-fpm/php-fpm.sock
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload
from https://github.com/terrylinooo/daily/wiki/Install-Nginx,-PHP-7,-MariaDB-10-(LEMP)-on-CentOS-7
------

CentOS7下,安装PHP7, NGINX & MySQL 5.6

建议CentOS 7.均为SSH下、root用户。
一、升级系统,更换更新源 适用于CentOS / RHEL 7系统
yum install epel-release
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
rpm -Uvh http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
适用于CentOS / RHEL 6系统
yum install epel-release
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el6/latest.rpm
rpm -Uvh http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm
二、安装PHP 7 1、安装PHP 7
yum install php70w
2、安装PHP 7组件 查找组件
yum search php70w
安装组件
yum install php70w-mysql php70w-xml php70w-soap php70w-xmlrpc
yum install php70w-mbstring php70w-json php70w-gd php70w-mcrypt
三、安装NGINX 1、安装NGINX
yum install nginx
2、启动NGINX
systemctl enable nginx.service
systemctl start nginx.service
四、安装MySQL 5.6 1、安装MySQL
yum install mysql-server
2、安全设置
systemctl start mysqld.service
mysql_secure_installation
3、启动MySQL
systemctl restart mysqld.service
systemctl enable mysqld.service
五、设置PHP-FPM
yum install php70w-fpm
六、创建网站
nano /etc/nginx/conf.d/example.conf
粘贴如下内容:
server {
        listen   80;
        root /var/www;
        index index.php index.html index.htm;
        server_name  example.com www.example.com;
        location / {
                try_files $uri $uri/ /index.html;
        }
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
        }
        location ~ .php$ {
                try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}
根据需要更改为自己的域名、文件存放目录。
七、重启服务
systemctl restart nginx.service
systemctl restart php-fpm.service
八、防火墙开放http (80) 和 https (443)端口
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload
via:https://servercheap.net/crm/index.php?rp=/knowledgebase/1/Install-PHP-7-NGINX-and-MySQL-56-on-CentOSorRHEL-71-and-67.html
--------------

通过YUM方式在CentOS 7中安装与配置nginx+php+mariadb

下面我们开始第一部分内容介绍:
安装环境 [root@1st ~]# cat /etc/redhat-release CentOS Linux release 7.2.1511 (Core)
[root@1st ~]# uname -an Linux 1st.iwshare.org 2.6.32-042stab113.21 #1 SMP Wed Mar 23 11:05:25 MSK 2016 x86_64 x86_64 x86_64 GNU/Linux
安装EPEL扩展: [root@1st ~]# yum install epel-release.noarch
安装NGINX [root@1st ~]# vim /etc/yum.repos.d/nginx.repo [nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/7/x86_64/ gpgcheck=0 enabled=1
[root@1st ~]# yum install nginx
安装PHP [root@1st ~]# rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm [root@1st ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
[root@1st ~]# yum install php70w php70w-fpm php70w-opcache php70w-common \ php70w-cli php70w-devel php70w-gd php70w-mbstring php70w-mcrypt \ php70w-mysqlnd php70w-pear.noarch php70w-xml php70w-xmlrpc \ php70w-pecl* php70w-tidy php70w-pdo php70w-process
安装MariaDB [root@1st ~]# vim /etc/yum.repos.d/MariaDB.repo # MariaDB 10.1 CentOS repository list – created 2016-05-19 00:06 UTC # http://mariadb.org/mariadb/repositories/ [mariadb] name = MariaDB baseurl = http://yum.mariadb.org/10.1/centos7-amd64 gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB gpgcheck=1
[root@1st ~]# yum install MariaDB-server MariaDB-client
到此,基本安装内容介绍完成.
下面我们开始第二部分内容介绍:
PHP的配置 [root@1st ~]# vim /etc/sysctl.conf #add line kernel.shmmax = 268435456
[root@1st ~]# sysctl -p

[root@1st ~]# more /etc/php-fpm.conf

;;;;;;;;;;;;;;;;;;;;; ; FPM Configuration ; ;;;;;;;;;;;;;;;;;;;;;
; All relative paths in this configuration file are relative to PHP’s install ; prefix. This prefix can be dynamically changed by using the ; ‘-p’ argument from the command line.
;;;;;;;;;;;;;;;;;; ; Global Options ; ;;;;;;;;;;;;;;;;;;
[global] ; Pid file ; Default Value: none pid = /var/run/php-fpm/php-fpm.pid
; Error log file ; If it’s set to “syslog”, log is sent to syslogd instead of being written ; in a local file. ; Default Value: log/php-fpm.log error_log = /var/log/php-fpm/error.log
; syslog_facility is used to specify what type of program is logging the ; message. This lets syslogd specify that messages from different facilities ; will be handled differently. ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON) ; Default Value: daemon ;syslog.facility = daemon
; syslog_ident is prepended to every message. If you have multiple FPM ; instances running on the same server, you can change the default value ; which must suit common needs. ; Default Value: php-fpm ;syslog.ident = php-fpm
; Log level ; Possible Values: alert, error, warning, notice, debug ; Default Value: notice log_level = error
; If this number of child processes exit with SIGSEGV or SIGBUS within the time ; interval set by emergency_restart_interval then FPM will restart. A value ; of ‘0’ means ‘Off’. ; Default Value: 0 emergency_restart_threshold = 0
; Interval of time used by emergency_restart_interval to determine when ; a graceful restart will be initiated. This can be useful to work around ; accidental corruptions in an accelerator’s shared memory. ; Available Units: s(econds), m(inutes), h(ours), or d(ays) ; Default Unit: seconds ; Default Value: 0 emergency_restart_interval = 0
; Time limit for child processes to wait for a reaction on signals from master. ; Available units: s(econds), m(inutes), h(ours), or d(ays) ; Default Unit: seconds ; Default Value: 0 process_control_timeout = 0
; The maximum number of processes FPM will fork. This has been design to control ; the global number of processes when using dynamic PM within a lot of pools. ; Use it with caution. ; Note: A value of 0 indicates no limit ; Default Value: 0 ; process.max = 128
; Specify the nice(2) priority to apply to the master process (only if set) ; The value can vary from -19 (highest priority) to 20 (lower priority) ; Note: – It will only work if the FPM master process is launched as root ; – The pool process will inherit the master process priority ; unless it specified otherwise ; Default Value: no set ; process.priority = -19
; Send FPM to background. Set to ‘no’ to keep FPM in foreground for debugging. ; Default Value: yes daemonize = yes
; Set open file descriptor rlimit for the master process. ; Default Value: system defined value ;rlimit_files = 1024
; Set max core size rlimit for the master process. ; Possible Values: ‘unlimited’ or an integer greater or equal to 0 ; Default Value: system defined value ;rlimit_core = 0
; Specify the event mechanism FPM will use. The following is available: ; – select (any POSIX os) ; – poll (any POSIX os) ; – epoll (linux >= 2.5.44) ; – kqueue (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0) ; – /dev/poll (Solaris >= 7) ; – port (Solaris >= 10) ; Default Value: not set (auto detection) ;events.mechanism = epoll
; When FPM is build with systemd integration, specify the interval, ; in second, between health report notification to systemd. ; Set to 0 to disable. ; Available Units: s(econds), m(inutes), h(ours) ; Default Unit: seconds ; Default value: 10 ;systemd_interval = 10
;;;;;;;;;;;;;;;;;;;; ; Pool Definitions ; ;;;;;;;;;;;;;;;;;;;;
; Multiple pools of child processes may be started with different listening ; ports and different management options. The name of the pool will be ; used in logs and stats. There is no limitation on the number of pools which ; FPM can handle. Your system will tell you anyway 🙂
; Include one or more files. If glob(3) exists, it is used to include a bunch of ; files from a glob(3) pattern. This directive can be used everywhere in the ; file. include=/etc/php-fpm.d/*.conf

[root@1st ~]# more /etc/php-fpm.d/www.conf

; Start a new pool named ‘www’. [www] ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user’s group ; will be used. ; RPM: apache Choosed to be able to access some dir as httpd user = apache ; RPM: Keep a group allowed to write in log dir. group = apache
; 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 IPv4 address on ; a specific port; ; ‘[ip:6:addr:ess]:port’ – to listen on a TCP socket to a specific IPv6 address on ; a specific port; ; ‘port’ – to listen on a TCP socket to all addresses ; (IPv6 and IPv4-mapped) on a specific port; ; ‘/path/to/unix/socket’ – to listen on a unix socket. ; Note: This value is mandatory. listen = 127.0.0.1:9000
; Set listen(2) backlog. ; Default Value: 511 (-1 on FreeBSD and OpenBSD) ;listen.backlog = 511
; 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 0660 listen.owner = nobody listen.group = nobody listen.mode = 0660 ; When POSIX Access Control Lists are supported you can set them using ; these options, value is a comma separated list of user/group names. ; When set, listen.owner and listen.group are ignored ;listen.acl_users = ;listen.acl_groups =
; List of addresses (IPv4/IPv6) 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,192.xxx.xxx.xxx (此处ip地址为监听80端口的ip地址)
; Specify the nice(2) priority to apply to the pool processes (only if set) ; The value can vary from -19 (highest priority) to 20 (lower priority) ; Note: – It will only work if the FPM master process is launched as root ; – The pool processes will inherit the master process priority ; unless it specified otherwise ; Default Value: no set ; process.priority = -19
; 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. With this process management, there will be ; always at least 1 children. ; 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. ; ondemand – no children are created at startup. Children will be forked when ; new requests will connect. The following parameter are used: ; pm.max_children – the maximum number of children that ; can be alive at the same time. ; pm.process_idle_timeout – The number of seconds after which ; an idle process 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 when pm is set to ‘dynamic’ or ‘ondemand’. ; 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 ‘static’, ‘dynamic’ or ‘ondemand’ ; Note: This value is mandatory. pm.max_children = 50
; 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) / 2 pm.start_servers = 10
; 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 = 5
; 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 = 35
; The number of seconds after which an idle process will be killed. ; Note: Used only when pm is set to ‘ondemand’ ; Default Value: 10s ;pm.process_idle_timeout = 10s;
; 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: 0 ;pm.max_requests = 500
; The URI to view the FPM status page. If this value is not set, no URI will be ; recognized as a status page. It shows the following informations: ; pool – the name of the pool; ; process manager – static, dynamic or ondemand; ; start time – the date and time FPM has started; ; start since – number of seconds since FPM has started; ; accepted conn – the number of request accepted by the pool; ; listen queue – the number of request in the queue of pending ; connections (see backlog in listen(2)); ; max listen queue – the maximum number of requests in the queue ; of pending connections since FPM has started; ; listen queue len – the size of the socket queue of pending connections; ; idle processes – the number of idle processes; ; active processes – the number of active processes; ; total processes – the number of idle + active processes; ; max active processes – the maximum number of active processes since FPM ; has started; ; max children reached – number of times, the process limit has been reached, ; when pm tries to start more children (works only for ; pm ‘dynamic’ and ‘ondemand’); ; Value are updated in real time. ; Example output: ; pool: www ; process manager: static ; start time: 01/Jul/2011:17:53:49 +0200 ; start since: 62636 ; accepted conn: 190460 ; listen queue: 0 ; max listen queue: 1 ; listen queue len: 42 ; idle processes: 4 ; active processes: 11 ; total processes: 15 ; max active processes: 12 ; max children reached: 0 ; ; By default the status page output is formatted as text/plain. Passing either ; ‘html’, ‘xml’ or ‘json’ in the 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 ; http://www.foo.bar/status?xml ; ; By default the status page only outputs short status. Passing ‘full’ in the ; query string will also return status for each pool process. ; Example: ; http://www.foo.bar/status?full ; http://www.foo.bar/status?json&full ; http://www.foo.bar/status?html&full ; http://www.foo.bar/status?xml&full ; The Full status returns for each process: ; pid – the PID of the process; ; state – the state of the process (Idle, Running, …); ; start time – the date and time the process has started; ; start since – the number of seconds since the process has started; ; requests – the number of requests the process has served; ; request duration – the duration in µs of the requests; ; request method – the request method (GET, POST, …); ; request URI – the request URI with the query string; ; content length – the content length of the request (only with POST); ; user – the user (PHP_AUTH_USER) (or ‘-‘ if not set); ; script – the main script called (or ‘-‘ if not set); ; last request cpu – the %cpu the last request consumed ; it’s always 0 if the process is not in Idle state ; because CPU calculation is done when the request ; processing has terminated; ; last request memory – the max amount of memory the last request consumed ; it’s always 0 if the process is not in Idle state ; because memory calculation is done when the request ; processing has terminated; ; If the process is in Idle state, then informations are related to the ; last request the process has served. Otherwise informations are related to ; the current request being served. ; Example output: ; ************************ ; pid: 31330 ; state: Running ; start time: 01/Jul/2011:17:53:49 +0200 ; start since: 63087 ; requests: 12808 ; request duration: 1250261 ; request method: GET ; request URI: /test_mem.php?N=10000 ; content length: 0 ; user: – ; script: /home/fat/web/docs/php/test_mem.php ; last request cpu: 0.00 ; last request memory: 0 ; ; Note: There is a real-time FPM status monitoring sample web page available ; It’s available in: @EXPANDED_DATADIR@/fpm/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 access log file ; Default: not set ;access.log = log/$pool.access.log
; The access log format. ; The following syntax is allowed ; %%: the ‘%’ character ; %C: %CPU used by the request ; it can accept the following format: ; – %{user}C for user CPU only ; – %{system}C for system CPU only ; – %{total}C for user + system CPU (default) ; %d: time taken to serve the request ; it can accept the following format: ; – %{seconds}d (default) ; – %{miliseconds}d ; – %{mili}d ; – %{microseconds}d ; – %{micro}d ; %e: an environment variable (same as $_ENV or $_SERVER) ; it must be associated with embraces to specify the name of the env ; variable. Some exemples: ; – server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e ; – HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e ; %f: script filename ; %l: content-length of the request (for POST request only) ; %m: request method ; %M: peak of memory allocated by PHP ; it can accept the following format: ; – %{bytes}M (default) ; – %{kilobytes}M ; – %{kilo}M ; – %{megabytes}M ; – %{mega}M ; %n: pool name ; %o: output header ; it must be associated with embraces to specify the name of the header: ; – %{Content-Type}o ; – %{X-Powered-By}o ; – %{Transfert-Encoding}o ; – …. ; %p: PID of the child that serviced the request ; %P: PID of the parent of the child that serviced the request ; %q: the query string ; %Q: the ‘?’ character if query string exists ; %r: the request URI (without the query string, see %q and %Q) ; %R: remote IP address ; %s: status (response code) ; %t: server time the request was received ; it can accept a strftime(3) format: ; %d/%b/%Y:%H:%M:%S %z (default) ; The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t ; %T: time the log has been written (the request has finished) ; it can accept a strftime(3) format: ; %d/%b/%Y:%H:%M:%S %z (default) ; The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag ; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t ; %u: remote user ; ; Default: “%R – %u %t \”%m %r\” %s” ;access.format = “%R – %u %t \”%m %r%Q%q\” %s %f %{mili}d %{kilo}M %C%%”
; The log file for slow requests ; Default Value: not set ; Note: slowlog is mandatory if request_slowlog_timeout is set slowlog = /var/log/php-fpm/www-slow.log
; 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 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
; 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. ; Note: relative path can be used. ; Default Value: current directory or / when chroot ;chdir = /var/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. ; Note: on highloaded environement, this can cause some delay in the page ; process time (several ms). ; Default Value: no ;catch_workers_output = yes
; Clear environment in FPM workers ; Prevents arbitrary environment variables from reaching FPM worker processes ; by clearing the environment in workers before env vars specified in this ; pool configuration are added. ; Setting to “no” will make all environment variables available to PHP code ; via getenv(), $_ENV and $_SERVER. ; Default Value: yes ;clear_env = no
; Limits the extensions of the main script FPM will allow to parse. This can ; prevent configuration mistakes on the web server side. You should only limit ; FPM to .php extensions to prevent malicious users to use other extensions to ; exectute php code. ; Note: set an empty value to allow all extensions. ; Default Value: .php ;security.limit_extensions = .php .php3 .php4 .php5 .php7
; 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/php-fpm/www-error.log php_admin_flag[log_errors] = on ;php_admin_value[memory_limit] = 128M
; Set session path to a directory owned by process user php_value[session.save_handler] = files php_value[session.save_path] = /var/lib/php/session php_value[soap.wsdl_cache_dir] = /var/lib/php/wsdlcache
启动PHP解析服务 [root@1st ~]# systemctl enable php-fpm.service Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
[root@1st ~]# systemctl start php-fpm.service [root@1st ~]# systemctl status php-fpm.service ● php-fpm.service – The PHP FastCGI Process Manager Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2016-05-31 21:05:43 EDT; 11s ago Main PID: 5043 (php-fpm) Status: “Processes active: 0, idle: 10, Requests: 0, slow: 0, Traffic: 0req/sec” CGroup: /system.slice/php-fpm.service ├─5043 php-fpm: master process (/etc/php-fpm.conf) ├─5044 php-fpm: pool www ├─5045 php-fpm: pool www ├─5046 php-fpm: pool www ├─5047 php-fpm: pool www ├─5048 php-fpm: pool www ├─5049 php-fpm: pool www ├─5050 php-fpm: pool www ├─5051 php-fpm: pool www ├─5052 php-fpm: pool www └─5053 php-fpm: pool www
May 31 21:05:43 186567 systemd[1]: Starting The PHP FastCGI Process Manager… May 31 21:05:43 186567 systemd[1]: Started The PHP FastCGI Process Manager.
NGINX的配置 [root@1st ~]# cd /etc/nginx/conf.d/ [root@1st conf.d]# vim allen.iwshare.me server { listen 80; server_name allen.iwshare.me;
#charset koi8-r; access_log /var/log/nginx/log/allen_iwshare_me.access.log main; error_log /var/log/nginx/log/allen_iwshare_me.error.log error;
root /documentroot/xxxx/iwshare.me; index index.php index.html index.htm;
location / { try_files $uri $uri/ /index.php?$query_string; }
#error_page 404 /404.html; # redirect server error pages to the static page /50x.htm # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; }
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
# deny access to .htaccess files, if Apache’s document root # concurs with nginx’s one # #location ~ /\.ht { # deny all; #} }
启动NGINX [root@1st ~]# systemctl start nginx
启动mariadb [root@1st ~]# systemctl start mariadb
到此,我们的nginx+php+mariadb环境构建完成,大家可以通过phpinfo进行测试.
---------------
LEMP w/ PHP7.2 (or 7.1) & MariaDB on Ubuntu 16/17/18 x64

Basic installation process of LEMP

Last update: 17/09/2018, tested on Ubuntu 18.04

Overview

This document is a list of notes when installing several Ubuntu LEMP instances w/ PHP7.2. With some sort of imagination it can be considered as a step-by-step tutorial of really basic installation process of LEMP. I wrote it mainly for myself, but feel free to use it. The LEMP consists of:
  • Nginx
  • PHP7.2 (php-fpm)
  • MariaDB
  • Optional: git, munin, rabbitmq, supervisor, node.js, Let's Encrypt, postfix

Table of Contents

Essentials

Installation script

To automatically install essentials, you can use the 👉 startup.sh script by downloading it and calling it with sudo sudo ./startup.sh. The file is deleted automatically.

Manual installation

If you want to have the installation in your hands, follow the manual installation. 👇

add new user

adduser admin

allow su without password for this user

echo "admin    ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

try new user

su - admin
exit

add authorized keys for that user

su - admin
mkdir .ssh
nano .ssh/authorized_keys
chmod 700 .ssh/
chmod 600 .ssh/authorized_keys

disable password login for all users

# Optional
echo "PasswordAuthentication no" | sudo tee --append /etc/ssh/sshd_config
sudo systemctl reload sshd
Or disable the password for some users only (admin, user_tld)
# Optional
sudo nano /etc/ssh/sshd_config
> Match User admin,user_tld
>    PasswordAuthentication no
sudo systemctl reload sshd

Fix locale if you are getting "WARNING! Your environment specifies an invalid locale."

sudo echo 'LC_ALL="en_US.UTF-8"' >> /etc/environment
# Log out & in

Set the correct timezone

sudo dpkg-reconfigure tzdata

Configure & Update APT

sudo apt-get -y dist-upgrade ; sudo apt-get -y update ; sudo apt-get -y upgrade
sudo apt-get -y install unattended-upgrades software-properties-common apache2-utils fail2ban

Install security updates automatically

sudo dpkg-reconfigure -plow unattended-upgrades

Install essentials

sudo apt-get -y install mc htop

Setup and configure Firewall

Open SSH port only.
sudo ufw allow 22 #OpenSSH
sudo ufw allow 80 #http
sudo ufw allow 443 #https
yes | sudo ufw enable
sudo ufw status

Webserver installation

You can skip steps 1-4 by downloading and running the lemp.sh script:
wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/lemp.sh && chmod u+x lemp.sh
sudo lemp.sh

1. Install Nginx

sudo add-apt-repository -y ppa:nginx/development && sudo apt-get update
sudo apt-get -y install nginx

2. Install MariaDB

sudo apt-get -y install mariadb-server # Or MySQL: sudo apt-get install mysql-server
sudo service mysql stop # Stop the MySQL if is running.
sudo mysql_install_db
sudo service mysql start
sudo mysql_secure_installation

3. Install PHP7.2

sudo add-apt-repository -y ppa:ondrej/php && sudo apt-get update
sudo apt-get -y install php7.2

4. Choose and install PHP7.2 modules

sudo apt-cache search php7.2-*
sudo apt-get -y install php7.2-fpm php7.2-curl php7.2-gd php7.2-json php7.2-mysql php7.2-sqlite3 php7.2-pgsql php7.2-bz2 php7.2-mbstring php7.2-soap php7.2-xml php7.2-zip

5. Check the installed PHP version

php -v

6. Configure Nginx

Configure /etc/nginx/nginx.conf

worker_processes auto;
events {
        use epoll;
        worker_connections 1024; # ~ RAM / 2
        multi_accept on;
}

Default vhost

cd /etc/nginx/sites-available
sudo rm default
sudo wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/nginx/sites-available/default
cd /etc/nginx/conf.d
sudo wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/nginx/conf.d/gzip.conf

Setup default settings for all virtual hosts

sudo mkdir -p /etc/nginx/conf.d/server/
cd /etc/nginx/conf.d/server/
sudo wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/nginx/conf.d/server/1-common.conf

Reload Nginx

sudo nginx -t && sudo nginx -s reload

Add new website, configuring PHP & Nginx & MariaDB

Steps 1. - 9. can be skipped by calling the add-vhost.sh. Just download add-vhost.shchmod u+x ./add-vhost.sh and call it sudo ./add-vhost.sh. The file is deleted automatically.
cd ~
wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/add-vhost.sh
chmod u+x add-vhost.sh
sudo ./add-vhost.sh

1. Create the dir structure for new website

sudo mkdir -p /var/www/vhosts/new-website.tld/{web,logs,ssl}

2. User groups and roles

sudo groupadd new-website
sudo useradd -g new-website -d /var/www/vhosts/new-website.tld new-website
sudo passwd new-website
You can switch users by using sudo su - new-website

3. Update permissions

sudo chown -R new-website:new-website /var/www/vhosts/new-website.tld
sudo chmod -R 0775 /var/www/vhosts/new-website.tld

4. Create new PHP-FPM pool for new site

sudo nano /etc/php/7.2/fpm/pool.d/new-website.tld.conf

5. Configure the new pool

[new-website]
user = new-website
group = new-website
listen = /run/php/php7.2-fpm-new-website.sock
listen.owner = www-data
listen.group = www-data
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_flag[allow_url_fopen] = off
pm = dynamic
pm.max_children = 5 # The hard-limit total number of processes allowed
pm.start_servers = 2 # When nginx starts, have this many processes waiting for requests
pm.min_spare_servers = 1 # Number spare processes nginx will create
pm.max_spare_servers = 3 # Number spare processes attempted to create
pm.max_requests = 500
chdir = /
5.1 Configuring pm.max_children
  1. Find how much RAM FPM consumes: ps -A -o pid,rss,command | grep php-fpm -> second row in bytes
    1. Reference: https://overloaded.io/finding-process-memory-usage-linux
  2. Eg. ~43904 / 1024 -> ~43MB per one process
  3. Calculation: If server has 2GB RAM, let's say PHP can consume 1GB (with some buffer, otherwise we can use 1.5GB): 1024MB / 43MB -> ~30MB -> pm.max_childern = 30
5.2 Configuring pm.start_serverspm.min_spare_serverspm.max_spare_servers
  1. pm.start_servers == number of CPUs
  2. pm.min_spare_servers = pm.start_servers / 2
  3. pm.max_spare_servers = pm.start_servers * 3

6. Restart PHP fpm and check it's running

sudo service php7.2-fpm restart
ps aux | grep new-site

7. Create new "vhost" for Nginx

sudo nano /etc/nginx/sites-available/new-site.tld

8. Configure the vhost

server {
    listen 80;

    root /var/www/vhosts/new-site.tld/web;
    index index.php index.html index.htm;

    server_name www.new-site.tld new-site.tld;

    include /etc/nginx/conf.d/server/1-common.conf;

    access_log /var/www/vhosts/new-site.tld/logs/access.log;
    error_log /var/www/vhosts/new-site.tld/logs/error.log warn;

    location ~ \.php$ {
        try_files $uri $uri/ /index.php?$args;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.2-fpm-new-site.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

9. Enable the new vhost

cd /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/new-site.tld new-site.tld
sudo nginx -t && sudo nginx -s reload

10. MariaDB (MySQL)

sudo mysql -u root
> CREATE DATABASE newwebsite_tld;
> CREATE USER 'newwebsite_tld'@'localhost' IDENTIFIED BY 'password';
> GRANT ALL PRIVILEGES ON newwebsite_tld.* TO 'newwebsite_tld'@'localhost';
> FLUSH PRIVILEGES;

Others

Git Aware Prompt

If you want to have nice git-aware prompt with some handy aliases, use this:
sudo su virtualhostuser
cd ~
mkdir ~/.bash && cd ~/.bash && git clone git://github.com/jimeh/git-aware-prompt.git && cd ~ && wget https://gist.githubusercontent.com/lucien144/56fbb184b1ec01fae1adf2e7abb626b6/raw/1d8a71172b1890adfe43d179f69fba66324b2014/.bashrcbashrc
bash
More information about aliases and other in this gist.

Git

sudo apt-get install git

Adminer

Adminer is a mostly MySQL database management tool. It's really tiny, simple & easy to use.
cd /etc/nginx/conf.d/server/
sudo wget https://raw.githubusercontent.com/lucien144/lemp-stack/master/nginx/conf.d/server/4-adminer.conf
sudo mkdir -p /var/www/html/adminer/
cd /var/www/html/adminer/
sudo wget https://www.adminer.org/latest.php -O index.php
sudo chmod a+x index.php
sudo htpasswd -c .htpasswd user
sudo nginx -t && sudo nginx -s reload
Adminer is now ready at http://{server.ip}/adminer/
Also, don't forget to change the username 👆.

Postfix (sending emails from PHP)

In case you cannot send emails from PHP and getting error (tail /var/log/mail.logNetwork is unreachable, you need to switch Postfix from IPv6 to IPv6.
sudo apt-get install postfix
sudo nano /etc/postfix/main.cf
Now change the line inet_protocols = all to inet_protocols = ipv4 and restart postfix by sudo /etc/init.d/postfix restart.
You can also check if you have opened port 25 by netstat -nutlap | grep 25

Munin

1. Install

apt-get install munin-node munin

2. Configure Munin

  1. Uncomment #host 127.0.0.1 in /etc/munin/munin-node.conf
  2. Append following code to /etc/munin/munin-node.conf
[nginx*]
env.url http://localhost/nginx_status

3. Configure nginx /etc/nginx/sites-available/default

sudo nano /etc/nginx/sites-available/default
# Change listen 80 default_server; to
listen 80

#Change listen [::]:80 default_server; to
listen [::]:80

# Add settings for stub status to server {}
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }

# Add setting to access stats online

    location /stats {
        allow YOUR.IP.ADDRESS;
        deny all;
        alias /var/cache/munin/www/;
    }

4. Install plugins

cd /usr/share/munin/plugins
sudo wget -O nginx_connection_request https://raw.github.com/munin-monitoring/contrib/master/plugins/nginx/nginx_connection_request
sudo wget -O nginx_status https://raw.github.com/munin-monitoring/contrib/master/plugins/nginx/nginx_status
sudo wget -O nginx_memory https://raw.github.com/munin-monitoring/contrib/master/plugins/nginx/nginx_memory

sudo chmod +x nginx_request
sudo chmod +x nginx_status
sudo chmod +x nginx_memory

sudo ln -s /usr/share/munin/plugins/nginx_request /etc/munin/plugins/nginx_request
sudo ln -s /usr/share/munin/plugins/nginx_status /etc/munin/plugins/nginx_status
sudo ln -s /usr/share/munin/plugins/nginx_memory /etc/munin/plugins/nginx_memory

Restart Munin

sudo service munin-node restart

Rabbitmq

Install PHP extension
sudo apt-get install php-amqp
Install RabbitMQ
echo 'deb http://www.rabbitmq.com/debian/ testing main' | sudo tee /etc/apt/sources.list.d/rabbitmq.list
wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get install rabbitmq-server
sudo service rabbitmq-server status
sudo rabbitmq-plugins enable rabbitmq_management
sudo ufw allow 15672
sudo rabbitmqctl add_user admin *********
sudo rabbitmqctl set_user_tags admin administrator
sudo rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"
sudo rabbitmqctl delete_user guest
sudo service rabbitmq-server restart

Installing plugin

  1. Download the .ez plugin to /usr/lib/rabbitmq/lib/rabbitmq_server-{version}/plugins
  2. Enable the plugin by sudo rabbitmq-plugins enable {plugin name}

Supervisor

sudo apt-get install supervisor

Enable the web interface

echo "
[inet_http_server]
port=9001
username=admin
password=*********" | sudo tee --append /etc/supervisor/supervisord.conf

sudo service supervisor reload
sudo ufw allow 9001
The interface should be available on http://{SERVER_IP}:9001/

Node.js & NPM

sudo apt-get install nodejs
sudo apt-get install npm
If you are getting error /usr/bin/env: ‘node’: No such file or directory run
sudo ln -s /usr/bin/nodejs /usr/bin/node

Composer

wget https://raw.githubusercontent.com/composer/getcomposer.org/1b137f8bf6db3e79a38a5bc45324414a6b1f9df2/web/installer -O - -q | php -- --quiet
sudo mv composer.phar /usr/local/bin/composer

Todo

Reference

Setting PHP-FPM

FROM https://github.com/lucien144/lemp-stack

No comments:

Post a Comment