高性能LNMP搭建(linux/nginx/mysql/php-fastcgi)

时间:2022-12-02 19:38:51

 

高性能LNMP搭建 (linux/nginx/mysql/php-fastcgi) 一、准备工作 1、关闭不必要的服务 Centos系统安装完毕之后,关闭不需要的服务优化系统,安装系统更新和所需软件支持。 关闭不需要的服务 chkconfig --level 3 acpid off chkconfig --level 3 anacron off chkconfig --level 3 apmd off chkconfig --level 3 mdmonitor off chkconfig --level 3 xinetd off chkconfig --level 3 sendmail off chkconfig --level 3 rpcgssd off chkconfig --level 3 rawdevices off chkconfig --level 3 messagebus off chkconfig --level 3 atd off chkconfig --level 3 gpm off chkconfig --level 3 autofs off chkconfig --level 3 cpuspeed off chkconfig --level 3 haldaemon off chkconfig --level 3 nfslock off chkconfig --level 3 portmap off chkconfig --level 3 xfs off chkconfig --level 3 netfs off chkconfig --level 3 smartd off chkconfig --level 3 ip6tables off chkconfig --level 3 isdn off chkconfig --level 3 rpcidmapd off chkconfig --level 3 microcode_ctl off service acpid stop service anacron stop service apmd stop service mdmonitor stop service xinetd stop service sendmail stop service rpcgssd stop service rawdevices stop service messagebus stop service atd stop service gpm stop service autofs stop service cpuspeed stop service haldaemon stop service nfslock stop service portmap stop service xfs stop service netfs stop service smartd stop service ip6tables stop service isdn stop service rpcidmapd stop service microcode_ctl stop 2、安装系统更新和所需软件支持 yum -y update yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers ntp rar 3、下载需要用到的软件包 (以下地址都是官方下载、也可以自己查找) 【下载PHP需要的库】 wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz wget http://ncu.dl.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.gz wget http://ncu.dl.sourceforge.net/project/mhash/mhash/0.9.9.9/mhash-0.9.9.9.tar.gz wget http://ncu.dl.sourceforge.net/project/mcrypt/MCrypt/2.6.8/mcrypt-2.6.8.tar.gz   【下载mysql、php、nginx】 wget http://mysql.mirrors.hoobly.com/Downloads/MySQL-5.1/mysql-5.1.57.tar.gz wget http://us.php.net/distributions/php-5.2.17.tar.gz wget http://php-fpm.org/downloads/php-5.2.17-fpm-0.5.14.diff.gz wget http://www.nginx.org/download/nginx-1.0.2.tar.gz wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.20.tar.gz   【下载php扩展】 wget http://pecl.php.net/get/memcache-2.2.6.tgz wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz wget http://jaist.dl.sourceforge.net/sourceforge/eaccelerator/eaccelerator-0.9.5.tar.bz2 wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick-6.7.6-8.tar.gz wget http://pecl.php.net/get/imagick-2.3.0.tgz   这个版本不要太高,否则会装不上 二、安装PHP需要的库程序 tar zxvf libiconv-1.13.1.tar.gz cd libiconv-1.13.1/ && ./configure --prefix=/usr/local make && make install && cd ..   tar zxvf libmcrypt-2.5.8.tar.gz cd libmcrypt-2.5.8/ && ./configure make && make install /sbin/ldconfig && cd libltdl/ && ./configure --enable-ltdl-install make && make install && cd ../..   tar zxvf mhash-0.9.9.9.tar.gz cd mhash-0.9.9.9/ && ./configure make && make install && cd ..   ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4 ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8 ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2 ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1 ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config tar zxvf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/ && /sbin/ldconfig
./configure && make && make install && cd ..
三、编译安装 MySQL 1、安装mysql程序 tar zxvf mysql-5.1.57.tar.gz && cd mysql-5.1.57 ./configure   -prefix=/data/mysql --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile 2、创建用户组和库 创建mysql用户组,创建数据库、日志等存储目录并赋予权限 mkdir -p /data/mysqldata mkdir -p /data/mysqldata/database mkdir -p /data/mysqldata/log mkdir -p /data/mysqldata/pid groupadd mysql useradd -g mysql -d /data/mysqldata/database -s /sbin/nologin mysql chgrp -R mysql /usr/local/webserver/mysql/. chown -R root:mysql /usr/local/webserver/mysql/* chown -R mysql:mysql /data/mysqldata/* 3、修改mysql的主配置文件 修改my.cnf文件参数(参数适用于大于2G内存服务器) cp -r support-files/my-medium.cnf   /etc/my.cnf chmod 755 /etc/my.cnf vi /etc/my.cnf # Example MySQL config file for medium systems. # # This is for a system with little memory (32M - 64M) where MySQL plays # an important part, or systems up to 128M where MySQL is used together with # other programs (such as a web server) # # MySQL programs look for option files in a set of # locations which depend on the deployment platform. # You can copy this option file to one of those # locations. For information about these locations, see: # http://dev.mysql.com/doc/mysql/en/option-files.html # # In this file, you can use all long options that a program supports. # If you want to know which options a program supports, run the program # with the "--help" option.   # The following options will be passed to all MySQL clients [client] #password       = your_password port           = 3306 socket                = /tmp/mysql.sock   # Here follows entries for some specific programs   # The MySQL server [mysqld] user          = mysql port           = 3306 socket                = /tmp/mysql.sock basedir              = /data/mysql datadir              = /data/mysqldata/database log-error = /data/mysqldata/log/mysql_error.log pid-file      = /data/mysqldata/pid/mysql.pid skip-external-locking skip-name-resolve back_log = 500 key_buffer_size = 256M max_allowed_packet = 32M thread_stack = 193K table_cache = 256 table_open_cache = 256 sort_buffer_size = 4M join_buffer_size = 4M net_buffer_length = 1M read_buffer_size = 4M read_rnd_buffer_size = 8M myisam_sort_buffer_size = 64M   thread_cache = 128 thread_cache_size = 10 query_cache_size = 32M tmp_table_size = 128M max_connections = 5000 wait_timeout = 60 max_connect_errors = 6000 expire_logs_days = 30   # Don't listen on a TCP/IP port at all. This can be a security enhancement, # if all processes that need to connect to mysqld run on the same host. # All interaction with mysqld must be made via Unix sockets or named pipes. # Note that using this option without enabling named pipes on Windows # (via the "enable-named-pipe" option) will render mysqld useless! # #skip-networking   # Replication Master Server (default) # binary logging is required for replication log-bin=mysql-bin   # binary logging format - mixed recommended binlog_format=mixed   # required unique id between 1 and 2^32 - 1 # defaults to 1 if master-host is not set # but will not function as a master if omitted server-id = 1   # Replication Slave (comment out master section to use this) # # To configure this host as a replication slave, you can choose between # two methods : # # 1) Use the CHANGE MASTER TO command (fully described in our manual) - #    the syntax is: # #    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>, #    MASTER_USER=<user>, MASTER_PASSWORD=<password> ; # #    where you replace <host>, <user>, <password> by quoted strings and #    <port> by the master's port number (3306 by default). # #    Example: # #    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306, #    MASTER_USER='joe', MASTER_PASSWORD='secret'; # # OR # # 2) Set the variables below. However, in case you choose this method, then #    start replication for the first time (even unsuccessfully, for example #    if you mistyped the password in master-password and the slave fails to #    connect), the slave will create a master.info file, and any later #    change in this file to the variables' values below will be ignored and #    overridden by the content of the master.info file, unless you shutdown #    the slave server, delete master.info and restart the slaver server. #    For that reason, you may want to leave the lines below untouched #    (commented) and instead use CHANGE MASTER TO (see above) # # required unique id between 2 and 2^32 - 1 # (and different from the master) # defaults to 2 if master-host is set # but will not function as a slave if omitted #server-id       = 2 # # The replication master for this slave - required #master-host     =   <hostname> # # The username the slave will use for authentication when connecting # to the master - required #master-user     =   <username> # # The password the slave will authenticate with when connecting to # the master - required #master-password =   <password> # # The port the master is listening on. # optional - defaults to 3306 #master-port     = <port> # # binary logging - not required for slaves, but recommended #log-bin=mysql-bin   # Uncomment the following if you are using InnoDB tables #innodb_data_home_dir = /data/mysql/var #innodb_data_file_path = ibdata1:10M:autoextend #innodb_log_group_home_dir = /data/mysql/var # You can set .._buffer_pool_size up to 50 - 80 % # of RAM but beware of setting memory usage too high #innodb_buffer_pool_size = 16M #innodb_additional_mem_pool_size = 2M # Set .._log_file_size to 25 % of buffer pool size #innodb_log_file_size = 5M #innodb_log_buffer_size = 8M #innodb_flush_log_at_trx_commit = 1 #innodb_lock_wait_timeout = 50   [mysqldump] quick max_allowed_packet = 32M   [mysql] no-auto-rehash # Remove the next comment character if you are not familiar with SQL #safe-updates   [myisamchk] key_buffer_size = 20M sort_buffer_size = 20M read_buffer = 2M write_buffer = 2M   [mysqlhotcopy] interactive-timeout     4、初始化MySQL服务 /data/mysql/bin/mysql_install_db   --basedir=/data/mysql   --datadir=/data/mysqldata/database   --user=mysql 5、启动MySQL服务 /data/mysql/mysql/bin/mysqld_safe --user=mysql &            //启动服务 /data/mysql/mysql/bin/mysqladmin -u root -p shutdown      //停止服务 6、修改root密码 /data/mysql/mysql/bin/mysqladmin -u root password ‘yourpassword’ 四、编译安装PHP(FastCGI模式) #tar -zxvf php-5.2.17.tar.gz #gzip   -cd php-5.2.17-fpm-0.5.14.diff.gz |patch -d php-5.2.17 -p1 #cd php-5.2.17 # ./buildconf   --force #./configure --prefix=/data/php --with-config-file-path=/data/php/etc --with-mysql=/data/mysql/   --with-mysqli=/data/mysql/bin/mysql_config   --with-gd --with-jpeg-dir --with-iconv-dir=/usr/local --with-libxml-dir=/usr --with-zlib --with-png-dir --with-curl --with-ldap --with-xmlrpc --with-openssl --with-mhash --with-mcrypt --with-freetype-dir --with-ldap-sasl --with-curlwrappers --enable-xml --enable-shared   --enable-discard-path --enable-safe-mode --enable-bcmath   --enable-shmop --enable-sysvsem --enable-inline-optimization --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect   --enable-mbstring=all   --enable-gd-native-ttf --enable-pcntl --enable-sockets --enable-zip --enable-soap #make ZEND_EXTRA_LIBS='-liconv' #make install # cp php.ini-dist /data/php/etc/php.ini 五、安装PHP扩展模块 1、安装扩展模块 tar zxvf memcache-2.2.6.tgz cd memcache-2.2.6/ /data/php/bin/phpize ./configure --with-php-config=/data/php/bin/php-config make && make install && cd ..   tar zxvf PDO_MYSQL-1.0.2.tgz cd PDO_MYSQL-1.0.2/ /data/php/bin/phpize ./configure --with-php-config=/data/php/bin/php-config --with-pdo-mysql=/data/mysql make && make install && cd ..   tar jxvf eaccelerator-0.9.6.1.tar.bz2 cd eaccelerator-0.9.6.1/ /data/php/bin/phpize ./configure --enable-eaccelerator=shared --with-php-config=/data/php/bin/php-config make && make install && cd ..    tar zxvf ImageMagick-6.7.0-8.tar.gz cd ImageMagick-6.7.0-8/ ./configure && make && make install && cd ..   tar zxvf imagick-2.3.0.tgz cd imagick-2.3.0/ /data/php/bin/phpize ./configure --with-php-config=/data/php/bin/php-config make && make install. 2、修改PHP配置文件php.ini # cd /data/php/etc # vim /data/php/etc/php.ini 查找: extension_dir = "./" 修改为: extension_dir = "/data/php/lib/php/extensions/no-debug-non-zts-20060613/" 并在此行后增加以下几行,然后保存: extension = "memcache.so" extension = "pdo_mysql.so" extension = "imagick.so" 再查找: output_buffering = Off 修改为: output_buffering = On 创建缓存目录,配置eAccelerator加速PHP: mkdir -p /data/eaccelerator_cache 将以下参数添加到php.ini文件末尾 zend_extension="/data/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so" eaccelerator.shm_size="64" eaccelerator.cache_dir="/data/eaccelerator_cache" eaccelerator.enable="1" eaccelerator.optimizer="1" eaccelerator.check_mtime="1" eaccelerator.debug="0" eaccelerator.filter="" eaccelerator.shm_max="0" eaccelerator.shm_ttl="3600" eaccelerator.shm_prune_period="3600" eaccelerator.shm_only="0" eaccelerator.compress="1" eaccelerator.compress_level="9" 3、修改php-fpm.conf配置文件 # cd /data/php/etc [root@loxhy etc]# vi php-fpm.conf      62                         Unix user of processes      63                         <value name="user">www</value>      64      65                         Unix group of processes      66                         <value name="group">www</value> 如果安装Nginx+PHP是为了程序调试,下边需要将0修改为1: 59                         <value name="display_errors">1</value> 这样能显示PHP的错误信息,否则Nginx会报状态500的空白页错误。 # /data/php/sbin/php-fpm start Starting php_fpm done 这样php-fpm就启动了。默认是9000端口。 # ps -ef |grep php  [root@loxhy etc]# netstat -anlp |grep 9000 tcp        0     0 127.0.0.1:9000      0.0.0.0:*    LISTEN   2596/php-cgi  #echo "/data/php/sbin/php-fpm start " >>/etc/rc.local 4、启动php-fpm    启动php-cgi进程,监听127.0.0.1的9000端口,进程数为128(如果服务器内存小于3GB,可以只开启64个进程),用户为:www
 ulimit -SHn 65535
/usr/local/webserver/php/sbin/php-fpm start         //在www用户创建之后在开启。
注:/usr/local/webserver/php/sbin/php-fpm 还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。 六、编译安装nginx 1、创建www用户和组,以及网站目录,日志目录 groupadd www useradd -g www -s /sbin/nologin www mkdir -p /data/wsdata/wwwroot mkdir -p /data/wsdata/wwwroot/error echo "404" > /data/wsdata/wwwroot/error/404.html echo "server is too busy" > /data/wsdata/wwwroot/error/50x.html chmod +w /data/wsdata/wwwroot mkdir -p /data/wslogs/wwwroot chmod 777 /data/wslogs/wwwroot chown -R www:www /data/wsdata/wwwroot   tar zxvf pcre-8.12.tar.gz && cd pcre-8.12/ ./configure && make && make install   tar zxvf nginx-1.0.2.tar.gz && cd nginx-1.0.2/ #./configure --user=www --group=www --prefix=/data/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-cc-opt='-O3' --with-cpu-opt=opteron --with-http_gzip_static_module make && make install 2、创建或修改nginx配置文件 # vi /data/nginx/conf/nginx.conf user www www; worker_processes 4; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; error_log /data/wslogs/nginx_error.log crit; #pid        logs/nginx.pid; pid   /data/nginx/nginx.pid; worker_rlimit_nofile 51200; events {     use epoll;     worker_connections 51200; }   http {     include       mime.types;     default_type application/octet-stream;     #charset gb2312;     #log_format main '$remote_addr - $remote_user [$time_local] "$request" '     #                  '$status $body_bytes_sent "$http_referer" '     #                  '"$http_user_agent" "$http_x_forwarded_for"';       #access_log logs/access.log main;     server_names_hash_bucket_size 128;     client_header_buffer_size 32k;     large_client_header_buffers 4 32k;     ignore_invalid_headers on;     recursive_error_pages on;     server_name_in_redirect off;       sendfile        on;     tcp_nopush     on;     tcp_nodelay    on;       #keepalive_timeout 0;     keepalive_timeout 65;   #fastcgi options  fastcgi_connect_timeout 300;  fastcgi_send_timeout 300;  fastcgi_read_timeout 300;    fastcgi_buffer_size 64k;  fastcgi_buffers 4 64k;  fastcgi_busy_buffers_size 128k;  fastcgi_temp_file_write_size 128k;  fastcgi_intercept_errors on;   #size limits  client_max_body_size 300m;  client_body_buffer_size 256k;    #gzip compression  gzip on;  gzip_min_length 1k;  gzip_buffers 4 16k;  gzip_http_version 1.1;  gzip_comp_level 2;  gzip_types text/plain text/css application/x-javascript application/xml;  gzip_vary on;   #limit_zone crawler $binary_remote_addr 10m; #virtual hosts options  include vhosts.conf;       server {         listen       80;         server_name localhost;         #charset koi8-r;        #access_log logs/host.access.log main;         location / {             root   html;             index index.html index.htm;         }         #error_page 404              /404.html;         # redirect server error pages to the static page /50x.html         #         error_page   500 502 503 504 /50x.html;         location = /50x.html {             root   html;         }         # proxy the PHP scripts to Apache listening on 127.0.0.1:80         #         #location ~ \.php$ {         #    proxy_pass   http://127.0.0.1;         #}         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000         #         #location ~ \.php$ {         #    root           html;         #    fastcgi_pass   127.0.0.1:9000;         #    fastcgi_index index.php;         #    fastcgi_param SCRIPT_FILENAME /scripts$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;         #}     }     # another virtual host using mix of IP-, name-, and port-based configuration     #     #server {     #    listen       8000;     #    listen       somename:8080;     #    server_name somename alias another.alias;       #    location / {     #        root   html;     #        index index.html index.htm;     #    }     #}     # HTTPS server     #     #server {     #    listen       443;     #    server_name localhost;     #    ssl                  on;     #    ssl_certificate      cert.pem;     #    ssl_certificate_key cert.key;     #    ssl_session_timeout 5m;     #    ssl_protocols SSLv2 SSLv3 TLSv1;     #    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;     #    ssl_prefer_server_ciphers   on;     #    location / {     #        root   html;     #        index index.html index.htm;     #    }     #} } 3、修改虚拟主机文件 # vi /data/nginx/conf/vhosts.conf server {  listen 80;  server_name www.linuxde.net linuxde.net;  access_log /data/wslogs/linuxde_www_access.log combined;  index index.html index.htm index.php;  root /data/wsdata/wwwroot/linuxde/www;  #error_page 404 = ./error/404.html;  #error_page 500 502 503 504 = ./error/50x.html; #linuxde.net 重定向到 www.linuxde.net  if ($host !~ "^www.linuxde.net$") {  rewrite ^(.*) http://www.linuxde.net$1 permanent;  }  location ~ .*.(php|php5)?$ {  #fastcgi_pass unix:/tmp/php-cgi.sock;  fastcgi_pass   127.0.0.1:9000;  fastcgi_index   index.php;  include enable_fcgi.conf;  }  location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {  access_log      off;  expires 30d;  }  location ~ .*.(js|css)$ {  access_log      off;  expires 1d;  } #wordpress伪静态  location / {  if (-f $request_filename/index.html){    rewrite (.*) $1/index.html break;  }  if (-f $request_filename/index.php){    rewrite (.*) $1/index.php;  }  if (!-f $request_filename){    rewrite (.*) /index.php;  }  } } # vi /data/nginx/conf/enable_fcgi.conf #PHP PATH_INFO bugs if ($request_filename ~* (.*).php) {  set $php_url $1; } if (!-e $php_url.php) {  return 403; }   fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE   nginx;   fastcgi_param QUERY_STRING   $query_string; fastcgi_param REQUEST_METHOD   $request_method; fastcgi_param CONTENT_TYPE   $content_type; fastcgi_param CONTENT_LENGTH   $content_length;   fastcgi_param SCRIPT_FILENAME   $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME   $fastcgi_script_name; fastcgi_param REQUEST_URI   $request_uri; fastcgi_param DOCUMENT_URI   $document_uri; fastcgi_param DOCUMENT_ROOT   $document_root; fastcgi_param SERVER_PROTOCOL   $server_protocol;   fastcgi_param REMOTE_ADDR   $remote_addr; fastcgi_param REMOTE_PORT   $remote_port; fastcgi_param SERVER_ADDR   $server_addr; fastcgi_param SERVER_PORT   $server_port; fastcgi_param SERVER_NAME   $server_name;   #for test fastcgi_param HTTP_ACCEPT_ENCODING gzip,deflate;   # PHP only, required if PHP was built with --enable-force-cgi-redirect fastcgi_param REDIRECT_STATUS    200;   4、启动nginx服务 # /data/nginx/sbin/nginx -t            //检测配置文件是否正确 # /data/nginx/sbin/nginx             //启动nginx 这样LNMP就搭建完成了。