php Safe_mode影响参数

[TABLE=1]

CentOS Linux下添加新硬盘并分区格式化

Linux磁带备份,所以我先添加一块硬盘,并相应的建立分区,格式化,然后挂载使用。下面看我操作的步骤:
1.先用Fdisk -l 来查看当前状态下磁盘情况

login as: root

[email protected]'s password:

Last login: Mon Mar  1 09:08:02 2010 from 172.16.0.16

[root@linux1 ~]# fdisk -lDisk /dev/hda: 5368 MB, 5368709120 bytes

255 heads, 63 sectors/track, 652 cylinders

Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot      Start         End      Blocks   Id  System

/dev/hda1   *           1          13      104391   83  Linux

/dev/hda2              14         652     5132767+  8e  Linux LVM

Disk /dev/hdb: 2147 MB, 2147483648 bytes

16 heads, 63 sectors/track, 4161 cylinders

Units = cylinders of 1008 * 512 = 516096 bytes

Disk /dev/hdb doesn't contain a valid partition table

上面红色标识行可以看出,我添加了一块新硬盘/dev/hdb,大小为2G,未分区格式化状态。

2.用Fdisk /dev/hdb来进行分区操作。

[root@linux1 ~]# fdisk /dev/hdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel. Changes will remain in memory only,
until you decide to write them. After that, of course, the previous
content won't be recoverable.

The number of cylinders for this disk is set to 4161.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

Command (m for help): n   //输入N表示新建一个分区
Command action
   e   extended
   p   primary partition (1-4)
p  //p 表示建立一个原始分区
Partition number (1-4): 1   //1 表示此分区编号为1.
First cylinder (1-4161, default 1): 1 //1表示使用默认起始柱面号.如果要分多个区的话,先盘算好要多大,再输入数字
Last cylinder or +size or +sizeM or +sizeK (1-4161, default 4161): // 输入: 回车 表示使用默认结束柱面号.即此分区使用整个硬盘空间

Using default value 4161

Command (m for help): w //保存分区

The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

3.再次查看当前分区状态:

[root@linux1 ~]# fdisk -l

Disk /dev/hda: 5368 MB, 5368709120 bytes
255 heads, 63 sectors/track, 652 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hda1   *           1          13      104391   83  Linux
/dev/hda2              14         652     5132767+  8e  Linux LVM

Disk /dev/hdb: 2147 MB, 2147483648 bytes
16 heads, 63 sectors/track, 4161 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hdb1               1        4161     2097112+  83  Linux

可以看出,已经出来了一个/dev/hdb1的新分区。下一步将其格式化,再使用

4.用mkfs.ext3格式化新分区

[root@linux1 ~]# mkfs.ext3 /dev/hdb1
mke2fs 1.39 (29-May-2006)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
262144 inodes, 524278 blocks
26213 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=536870912
16 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376, 294912

Writing inode tables: done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 32 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

5.挂载使用。

[root@linux1 ~]# mkdir /mnt/hdb1   //新建一个挂载点。
[root@linux1 ~]# mount /dev/hdb1 /mnt/hdb1 //挂载。
[root@linux1 ~]# df -h
文件系统              容量  已用 可用 已用% 挂载点
/dev/mapper/VolGroup00-LogVol00
                      4.3G  3.6G  487M  89% /
/dev/hda1              99M   12M   82M  13% /boot
tmpfs                 125M     0  125M   0% /dev/shm
/dev/hdb1             2.0G  3.0M  1.9G   1% /mnt/hdb1

6 .开机自动挂载
三.设置新硬盘开机自动挂载

在/etc/fstab中添加新硬盘的挂载信息.添加下面一行:

/dev/hdb1 /mnt/hdb1 ext3 defaults 1 2(如果还有一个分区就是1 3,以此类推)

这样,每次开机后,系统会自动将/dev/hdb1挂载到/mnt/hdb1上

Mysql数据库优化技术之配置篇、索引篇[转]

 

(一)减少数据库访问

对于可以静态化的页面,尽可能静态化

对一个动态页面中可以静态的局部,采用静态化

部分数据可以生成XML,或者文本文件形式保存

使用数据缓存技术,例如: MemCached

(二)优化的检测方法

1.用户体验检测

2.Mysql状态检测

在Mysql命令行里面使用show status命令,得到当前mysql状态。

主要关注下列属性:

key_read_requests (索引读的请求数)(key_buffer_size设置影响)

key_reads(索引读响应数)

Key_blocks_used

Qcache_*

Open_tables(通过table_cache的设置影响)

Opened_tables

table_locks

3. 第三方工具检测

mysqlreporthttp://hackmysql.com/mysqlreport

mytophttp://jeremy.zawodny.com/mysql/mytop/
系统及Mysql的Log

系统命令: top, sar

Mysql的Log: slow_query.log

(三)硬件方面的优化

硬件方面,最容易成为Mysql瓶颈的部分是磁盘,其次是CPU和内存

磁盘方面

使用更快的磁盘,会对Mysql有很好的帮助

使用更多的硬盘,通过Raid,可以提高单块磁盘速度的问题

对于Raid方式,建议采用Raid 0+1 或者 Raid 1+0
CPU

毫无疑问,更高主频的CPU和更多的CPU数量可以给Mysql更

高的性能
内存

更高的内存,往往可以让Mysql中的更多的数据缓存在内存中,

但是,一个重要的因素是,需要有正确的Mysql的配置
网卡

使用千兆网卡及千兆网络
(四)操作系统方面的优化

1.不使用交换区。如果内存不足,增加更多的内存或配置你的系统使用较少内存
2. 不要使用NFS磁盘
3.增加系统和MySQL服务器的打开文件数量

使用ulimit –n 65535
4.增加系统的进程和线程数量。
5.关闭不必要的应用,优化硬盘参数,使用hdparm测试

(五)应用级的优化

1.使用多服务器负载均衡(多台读和写,用复制技术进行数据同步)
2.表的分区 (自定义分区,mysql5.1开始支持自带分区功能)
3.使用数据缓存技术memcached

(六)Mysql配置的优化

1.key_buffer(=512):索引缓冲使用的内存数量

这对MyISAM表来说非常重要,设定在可用内存的25%-30%较好,通过检查状态值 Key_read_requests和 Key_reads,

可以知道key_buffer设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好 ,否则说明 key_buffer 设置有点偏小
2.innodb_buffer_pool_size(= 512):索引缓冲使用的内存数量

3.table_cache (=1024):数据表缓存区的尺寸

每当 MySQL 访问一个表时,如果在表缓冲区中还有空间,该表就被打开并放入其中,这样可以更快地访问表内容。

通过检查运行峰值时间的 Open_tables 和 Opened_tables 状态值,可以决定是否需要调整 table_cache 的值。

如果你发现 open_tables 的值等于 table_cache,并且发现 opened_tables 状态值在不断增长,那么你就需要增加 table_cache 参数值了,

也不能盲目地把 table_cache 参数设置成很大的值,如果设置得太高,可能会造成文件描述符不足,从而造成性能不稳定或者连接失败。
4.sort_buffer_size (=256):指定排序用缓冲区的长度

该参数对应的分配内存是每连接独占!如果有100个连接,那么实际分配的总共排序缓冲区大小为100 × 6 = 600MB。

所以,对于内存在4GB左右的服务器推荐设置为6-8M
5.join_buffer_size :关联查询用缓冲区的长度

4G内存以上,建议大于32M,该参数对应的分配内存也是每连接独享!

6.max_connections (=1024):可以复用的线程数量

允许同时连接MySQL服务器的客户数量 ,可以观察和估计系统在峰值最大的并发连接数来设置
7.thread_cache(=*):可以复用的线程数量

一般设置为CPU数×2
8.innodb_buffer_pool_size(= 512):innodb表缓存池大小

这对Innodb表来说非常重要。Innodb相比MyISAM表对缓冲更为敏感。MyISAM可以在默认的 key_buffer_size 设置下运行的可以,

然而Innodb在默认的innodb_buffer_pool_size 设置下却跟蜗牛似的。

由于Innodb把数据和索引都缓存起来,无需留给操作系统太多的内存,因此如果只需要用Innodb的话则可以设置它高达 70-80% 的可用内存。

一些应用于 key_buffer 的规则有 — 如果你的数据量不大,并且不会暴增,那么无需把innodb_buffer_pool_size 设置的太大了.

9.innodb_flush_logs_at_trx_commit(=1) :事务提交后的日志刷新模式

是否为Innodb比MyISAM慢1000倍而头大?看来也许你忘了修改这个参数了。默认值是 1,这意味着每次提交的更新事务(或者每个事务之外的语句)都会刷新到磁盘中,

而这相当耗费资源,尤其是没有电池备用缓存时。很多应用程序,尤其是从 MyISAM转变过来的那些,把它的值设置为 2 就可以了,也就是不把日志刷新到磁盘上,

而只刷新到操作系统的缓存上。日志仍然会每秒刷新到磁盘中去,因此通常不会丢失每秒1-2次更新的消耗。如果设置为0就快很多了,不过也相对不安全了,

MySQL服务器崩溃时就会丢失一些事务。设置为2指挥丢失刷新到操作系统缓存的那部分事务.

 

(七)表的优化

1. 选择合适的数据引擎

MyISAM:适用于大量的读操作的表

InnoDB:适用于大量的写读作的表

2.选择合适的列类型

使用 SELECT * FROM TB_TEST PROCEDURE ANALYSE()可以对这个表的每一个字段进行分析,给出优化列类型建议

3.对于不保存NULL值的列使用NOT NULL,这对你想索引的列尤其重要

4.建立合适的索引

5.使用定长字段,速度比变长要快

 

(八)建立索引原则

1.合理使用索引

一个Table在一次query中只能使用一个索引,使用EXPLAIN语句来检验优化程序的操作情况

使用analyze帮助优化程序对索引的使用效果做出更准确的预测

2.索引应该创建在搜索、排序、归组等操作所涉及的数据列上

3.尽量将索引建立在重复数据少的数据列中,唯一所以最好

例如:生日列,可以建立索引,但性别列不要建立索引

4.尽量对比较短的值进行索引

降低磁盘IO操作,索引缓冲区中可以容纳更多的键值,提高命中率

如果对一个长的字符串建立索引,可以指定一个前缀长度

5.合理使用多列索引

如果多个条件经常需要组合起来查询,则要使用多列索引(因为一个表一次查询只能使用一个索引,建立多个单列索引也只能使用一个)

6.充分利用最左前缀

也就是要合理安排多列索引中各列的顺序,将最常用的排在前面

7.不要建立过多的索引

只有经常应用于where,order by,group by中的字段需要建立索引.

8.利用慢查询日志查找出慢查询(log-slow-queries, long_query_time)

 

(九)充分利用索引

1.尽量比较数据类型相同的数据列

2.尽可能地让索引列在比较表达式中独立, WHERE mycol < 4 / 2 使用索引,而WHERE mycol * 2 < 4不使用

3.尽可能不对查询字段加函数,

如WHERE YEAR(date_col) < 1990改造成WHERE date_col < ’1990-01-01’

WHERE TO_DAYS(date_col) – TO_DAYS(CURDATE()) < cutoff 改造成WHERE date_col < DATE_ADD(CURDATE(), INTERVAL cutoff DAY)

4.在LIKE模式的开头不要使用通配符

5.使用straight join可以强制优化器按照FROM子句的次序来进行联结,可以select straight join,强制所有联结,也可以select * from a straight join b强制两个表的顺序.

6.使用force index强制使用指定的索引.如 select * from song_lib force index(song_name) order by song_name比不用force index效率高

7.尽量避免使用MySQL自动类型转换,否则将不能使用索引.如将int型的num_col用where num_col=‘5’

(十)SQL语句的优化

1.创建合适的统计中间结果表,降低从大表查询数据的几率

2.尽量避免使用子查询,而改用连接的方式.例如:

SELECT a.id, (SELECT MAX(created) FROM posts WHERE author_id = a.id) AS latest_post

FROM authors a

可以改成:

SELECT a.id, MAX(p.created) AS latest_post

FROM authors AS a

INNER JOIN posts p ON (a.id = p.author_id)

GROUP BY a.id

select song_id from song_lib where singer_id in

(select singer_id from singer_lib

where first_char=’A’

) limit 2000改成:

select song_id from song_lib a

inner join singer_lib b on a.singer_id=b.singer_id and first_char=’A’ limit 2000

3.插入判断重复键时,使用ON DUPLICATE KEY UPDATE :

insert into db_action.action_today(user_id,song_id,action_count) values(1,1,1) ON DUPLICATE KEY UPDATE action_count=action_count+1;

4.避免使用游标

游标的运行效率极低,可以通过增加临时表,运用多表查询,多表更新等方式完成任务,不要使用游标.

(十一)使用Explain分析SQL语句使用索引的情况

当 你在一条SELECT语句前放上关键词EXPLAIN,MySQL解释它将如何处理SELECT,提供有关表如何联结和以什么次序联结的信息,借助于 EXPLAIN,可以知道什么时候必须为表加入索引以得到一个使用索引来寻找记录的更快的SELECT,你也能知道优化器是否以一个最佳次序联结表。为了 强制优化器对一个SELECT语句使用一个特定联结次序,增加一个STRAIGHT_JOIN子句。 。

EXPLAIN命令的一般语法是:EXPLAIN <SQL命令> 如:explain select * from a inner join b on a.id=b.id

EXPLAIN的分析结果参数详解:

1.table:这是表的名字。

2.type:连接操作的类型。

system:表中仅有一条记录(实际应用很少只有一条资料的表)

const:表最多有一个匹配行,用于用常数值比较PRIMARY KEY或UNIQUE索引的所有部分时,

如:select * from song_lib where song_id=2(song_id为表的primary key)

eq_ref:对于每个来自于前面的表的行组合,从该表中用UNIQUE或PRIMARY KEY的索引读取一行,

如:select * from song_lib a inner join singer_lib b on a.singer_id=b.singer_id(b的type值为eq_ref)

ref:对于每个来自于前面的表的行组合,从该表中用非UNIQUE或PRIMARY KEY的索引读取一行

如:select * from song_lib a inner join singer_lib b on a.singer_name=b.singer_name和

select * from singer_lib b where singer_name=‘ccc’ (b的type值为ref,因为b.singer_name是普通索引)

ref_or_null:该联接类型如同ref,但是添加了MySQL可以专门搜索包含NULL值的行,

如:select * from singer_lib where singer_name=‘ccc’ or singer_name is null

index_merge:该联接类型表示使用了索引合并优化方法

Key: 它显示了MySQL实际使用的索引的名字。如果它为空(或NULL),则MySQL不使用索引。

key_len: 索引中被使用部分的长度,以字节计。

3.ref:ref列显示使用哪个列或常数与key一起从表中选择行

4.rows: MySQL所认为的它在找到正确的结果之前必须扫描的记录数。显然,这里最理想的数字就是1。

5.Extra:这里可能出现许多不同的选项,其中大多数将对查询产生负面影响。一般有:

using where:表示使用了where条件

using filesort: 表示使用了文件排序,也就是使用了order by子句,并且没有用到order by 里字段的索引,从而需要

额外的排序开销,所以如果出现using filesort就表示排序的效率很低,需要进行优化,比如采用强制索引

的方法(force index)

===============================================

mysql 优化 (show variables, show status)。

 

 

安装好mysql后,配制文件应该在 /usr/local/mysql/share/mysql目录中,配制文件有几个,有my- huge.cnf my-medium.cnf my-large.cnf my-small.cnf,不同的流量的网站和不同配制的服务器环境,当然需要有不同的配制文件了。

一般的情 况下,my-medium.cnf这个配制文件就能满足我们的大多需要;一般我们会把配置文件拷贝到/etc/my.cnf 只需要修改这个配置文件就可以了,使用mysqladmin variables extended-status –u root –p 可以看到目前的参数,有3个配置参数是最重要的,即key_buffer_size,query_cache_size,table_cache。

key_buffer_size只对MyISAM表起作用,

key_buffer_size 指定索引缓冲区的大小,它决定索引处理的速度,尤其是索引读的速度。一般我们设为16M,实际上稍微大一点的站点 这个数字是远远不够的,通过检查状态值 Key_read_requests和Key_reads,可以知道key_buffer_size设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好(上述状态值可以使用SHOW STATUS LIKE ‘key_read%’获得)。 或者如果你装了phpmyadmin 可以通过服务器运行状态看到,笔者推荐用phpmyadmin管理mysql,以下的状态值都是本人通过phpmyadmin获得的实例分析:

这个服务器已经运行了20天

key_buffer_size – 128M
key_read_requests – 650759289
key_reads – 79112

比例接近1:8000 健康状况非常好

另外一个估计key_buffer_size的办法 把你网站数据库的每个表的索引所占空间大小加起来看看以此服务器为例:比较大的几个表索引加起来大概125M 这个数字会随着表变大而变大。

从4.0.1开始,MySQL提供了查询缓冲机制。使用查询缓冲,MySQL将SELECT语句和查询结果存放在缓冲区中,今后对于同样的SELECT语句(区分大小写),将直接从缓冲区中读取结果。根据MySQL用户手册,使用查询缓冲最多可以达到238%的效率。

通过调节以下几个参数可以知道query_cache_size设置得是否合理

Qcache inserts
Qcache hits
Qcache lowmem prunes
Qcache free blocks
Qcache total blocks

Qcache_lowmem_prunes 的值非常大,则表明经常出现缓冲不够的情况,同时Qcache_hits的值非常大,则表明查询缓冲使用非常频繁,此时需要增加缓冲大小 Qcache_hits的值不大,则表明你的查询重复率很低,这种情况下使用查询缓冲反而会影响效率,那么可以考虑不用查询缓冲。此外,在SELECT语 句中加入SQL_NO_CACHE可以明确表示不使用查询缓冲。

Qcache_free_blocks,如果该值非常大,则表明缓冲区中碎片很多query_cache_type指定是否使用查询缓冲

我设置:

query_cache_size = 32M
query_cache_type= 1

得到如下状态值:

Qcache queries in cache 12737 表明目前缓存的条数
Qcache inserts 20649006
Qcache hits 79060095  看来重复查询率还挺高的
Qcache lowmem prunes 617913 有这么多次出现缓存过低的情况
Qcache not cached 189896
Qcache free memory 18573912  目前剩余缓存空间
Qcache free blocks 5328 这个数字似乎有点大 碎片不少
Qcache total blocks 30953

如果内存允许32M应该要往上加点

table_cache 指定表高速缓存的大小。每当MySQL访问一个表时,如果在表缓冲区中还有空间,该表就被打开并放入其中,这样可以更快地访问表内容。通过检查峰值时间的 状态值Open_tables和Opened_tables,可以决定是否需要增加table_cache的值。如果你发现open_tables等于 table_cache,并且opened_tables在不断增长,那么你就需要增加table_cache的值了(上述状态值可以使用SHOW STATUS LIKE ‘Open%tables’获得)。注意,不能盲目地把table_cache设置成很大的值。如果设置得太高,可能会造成文件描述符不足,从而造成性能 不稳定或者连接失败。

对于有1G内存的机器,推荐值是128-256。

笔者设置table_cache = 256

得到以下状态:

Open tables 256
Opened tables 9046

虽 然open_tables已经等于table_cache,但是相对于服务器运行时间来说,已经运行了20天,opened_tables的值也非常低。 因此,增加table_cache的值应该用处不大。如果运行了6个小时就出现上述值 那就要考虑增大table_cache。

如果你不 需要记录2进制log 就把这个功能关掉,注意关掉以后就不能恢复出问题前的数据了,需要您手动备份,二进制日志包含所有更新数据的语句,其目的是在恢复数据库时用它来把数据尽 可能恢复到最后的状态。另外,如果做同步复制( Replication )的话,也需要使用二进制日志传送修改情况。

log_bin指 定日志文件,如果不提供文件名,MySQL将自己产生缺省文件名。MySQL会在文件名后面自动添加数字引,每次启动服务时,都会重新生成一个新的二进制 文件。此外,使用log-bin-index可以指定索引文件;使用binlog-do-db可以指定记录的数据库;使用binlog-ignore- db可以指定不记录的数据库。注意的是:binlog-do-db和binlog-ignore-db一次只指定一个数据库,指定多个数据库需要多个语 句。而且,MySQL会将所有的数据库名称改成小写,在指定数据库时必须全部使用小写名字,否则不会起作用。

关掉这个功能只需要在他前面加上#号

#log-bin

开启慢查询日志( slow query log ) 慢查询日志对于跟踪有问题的查询非常有用。它记录所有查过long_query_time的查询,如果需要,还可以记录不使用索引的记录。下面是一个慢查询日志的例子:

开启慢查询日志,需要设置参数log_slow_queries、long_query_times、log-queries-not-using-indexes。

log_slow_queries 指定日志文件,如果不提供文件名,MySQL将自己产生缺省文件名。long_query_times指定慢查询的阈值,缺省是10秒。log- queries-not-using-indexes是4.1.0以后引入的参数,它指示记录不使用索引的查询。笔者设置 long_query_time=10

笔者设置:

sort_buffer_size = 1M
max_connections=120
wait_timeout =120
back_log=100
read_buffer_size = 1M
thread_cache=32
interactive_timeout=120
thread_concurrency = 4

参数说明:

back_log

要 求MySQL能有的连接数量。当主要MySQL线程在一个很短时间内得到非常多的连接请求,这就起作用,然后主线程花些时间(尽管很短) 检查连接并且启动一个新线程。back_log值指出在MySQL暂时停止回答新请求之前的短时间内多少个请求可以被存在堆栈中。只有如果期望在一个短时 间内有很多连接,你需要增加它,换句话说,这值对到来的TCP/IP连接的侦听队列的大小。你的操作系统在这个队列大小上有它自己的限制。 Unix listen(2)系统调用的手册页应该有更多的细节。检查你的OS文档找出这个变量的最大值。试图设定back_log高于你的操作系统的限制将是无效 的。

max_connections

并发连接数目最大,120 超过这个值就会自动恢复,出了问题能自动解决

thread_cache

没找到具体说明,不过设置为32后 20天才创建了400多个线程 而以前一天就创建了上千个线程 所以还是有用的

thread_concurrency

#设置为你的cpu数目x2,例如,只有一个cpu,那么thread_concurrency=2
#有2个cpu,那么thread_concurrency=4
skip-innodb
#去掉innodb支持

代码:
[client]
#password = your_password
port = 3306
socket = /tmp/mysql.sock
#socket = /var/lib/mysql/mysql.sock
# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port = 3306
socket = /tmp/mysql.sock
#socket = /var/lib/mysql/mysql.sock
skip-locking
key_buffer = 128M
max_allowed_packet = 1M
table_cache = 256
sort_buffer_size = 1M
net_buffer_length = 16K
myisam_sort_buffer_size = 1M
max_connections=120
#addnew config
wait_timeout =120
back_log=100
read_buffer_size = 1M
thread_cache=32
skip-innodb
skip-bdb
skip-name-resolve
join_buffer_size=512k
query_cache_size = 32M
interactive_timeout=120
long_query_time=10
log_slow_queries= /usr/local/mysql4/logs/slow_query.log
query_cache_type= 1
# Try number of CPU’s*2 for thread_concurrency
thread_concurrency = 4
[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[myisamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

补充

优 化table_cachetable_cache指定表高速缓存的大小。每当MySQL访问一个表时,如果在表缓冲区中还有空间,该表就被打开并放入其 中,这样可以更快地访问表内容。通过检查峰值时间的状态值Open_tables和Opened_tables,可以决定是否需要增加 table_cache的值。如果你发现open_tables等于table_cache,并且opened_tables在不断增长,那么你就需要增 加table_cache的值了(上述状态值可以使用SHOW STATUS LIKE ‘Open%tables’获得)。注意,不能盲目地把table_cache设置成很大的值。如果设置得太高,可能会造成文件描述符不足,从而造成性能 不稳定或者连接失败。对于有1G内存的机器,推荐值是128-256。

案例1:该案例来自一个不是特别繁忙的服务器 table_cache – 512open_tables – 103 opened_tables – 1273 uptime – 4021421 (measured in seconds)该案例中table_cache似乎设置得太高了。在峰值时间,打开表的数目比table_cache要少得多。

案例 2:该案例来自一台开发服务器。table_cache – 64open_tables – 64opened-tables – 431uptime – 1662790 (measured in seconds)虽然open_tables已经等于table_cache,但是相对于服务器运行时间来说,opened_tables的值也非常低。 因此,增加table_cache的值应该用处不大。
案例3:该案例来自一个upderperforming的服务器table_cache – 64 open_tables – 64 opened_tables – 22423uptime – 19538该案例中table_cache设置得太低了。虽然运行时间不到6小时,open_tables达到了最大值,opened_tables的值 也非常高。这样就需要增加table_cache的值。优化key_buffer_sizekey_buffer_size指定索引缓冲区的大小,它决定 索引处理的速度,尤其是索引读的速度。通过检查状态值Key_read_requests和Key_reads,可以知道key_buffer_size 设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好(上述状态值可以使用SHOW STATUS LIKE ‘key_read%’获得)。key_buffer_size只对MyISAM表起作用。即使你不使用MyISAM表,但是内部的临时磁盘表是 MyISAM表,也要使用该值。可以使用检查状态值created_tmp_disk_tables得知详情。对于1G内存的机器,如果不使用 MyISAM表,推荐值是16M(8-64M)。

案例1:健康状况key_buffer_size – 402649088 (384M) key_read_requests – 597579931 key_reads – 56188案例2:警报状态key_buffer_size – 16777216 (16M)key_read_requests – 597579931key_reads – 53832731案例1中比例低于1:10000,是健康的情况;案例2中比例达到1:11,警报已经拉响。

================================

Mysql调优中两个重要参数table_cache和key_buffer

本文根据我自己的一点经验,讨论了Mysql服务器优化中两个非常重要的参数,分别是table_cache,key_buffer_size。table_cache 指示表高速缓存的大小。当Mysql访问一个表时,如果在Mysql表缓冲区中还有空间,那么这个表就被打开并放入表缓冲区,这样做的好处是可以更快速地 访问表中的内容。一般来说,可以通过查看数据库运行峰值时间的状态值Open_tables和Opened_tables,用以判断是否需要增加 table_cache的值,即如果open_tables接近table_cache的时候,并且Opened_tables这个值在逐步增加,那就要 考虑增加这个值的大小了。

在mysql默认安装情况下,table_cache的值在2G内存以下的机器中的值默认时256到 512,如果机器有4G内存,则默认这个值是2048,但这决意味着机器内存越大,这个值应该越大,因为table_cache加大后,使得mysql对 SQL响应的速度更快了,不可避免的会产生更多的死锁(dead lock),这样反而使得数据库整个一套操作慢了下来,严重影响性能。所以平时维护中还是要根据库的实际情况去作出判断,找到最适合你维护的库的 table_cache值,有人说:“性能优化是一门艺术”,这话一点没错。大凡艺术品,大都是经过千锤百炼,精雕细琢而成。

这里还要说明一个问题,就是table_cache加大后碰到文件描述符不够用的问题,在mysql的配置文件中有这么一段提示

引用
“The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires.
Therefore you have to make sure to set the amount of open files allowed to at least 4096 in the variable “open-files-limit” in” section [mysqld_safe]”
说 的就是要注意这个问题,一想到这里,部分兄弟可能会用ulimit -n 作出调整,但是这个调整实际是不对的,换个终端后,这个值又会回到原始值,所以最好用sysctl或者修改/etc/sysctl.conf文件,同时还 要在配置文件中把open_files_limit这个参数增大,对于4G内存服务器,相信现在购买的服务器都差不多用4G的了,那这个这个 open_files_limit至少要增大到4096,如果没有什么特殊情况,设置成8192就可以了。

下面说说key_buffer_size这个参数,key_buffer_sizeO表示索引缓冲区的大小,严格说是它决定了数据库索引处理的速度,尤 其是索引读的速度。根据网络一些高手写的文章表示可以检查状态值Key_read_requests和Key_reads,即可知道 key_buffer_size设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好,虽然我还没有找到理论的依据,但是,我在自己维护的几台实际运 行良好的库做过的测试后表明,这个比值接近1:20000,这从结果证明了他们说这话的正确性,我们不妨用之。

后记:
我前面说过,性能优化是一件细活,影响mysql性能的因素很多,本文中只是选取了其中我认为比较重要的两个参数,期待和网友一起探讨更多mysql性能优化的技术。

 

 

Linux 设置用nobody用户执行crontab

方法一:

[root@localhost ~]# crontab -e -u nobody

输入

0 3 * * * /usr/local/php/bin/php /data/htdocs/crontab.php > /dev/null

方法二:当前用户设置

[root@localhost ~]# crontab -e

输入

30 1 * * * su -c '/data/htdocs/crontab.php' -s /usr/local/php/bin/php nobody

Nginx 0.8.x + PHP 5.2.10(FastCGI)搭建胜过Apache十倍的Web服务器(第5版)[转载]

Nginx (“engine x”) 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过两年半了。Igor 将源代码以类BSD许可证的形式发布。

Nginx 超越 Apache 的高性能和稳定性,使得国内使用 Nginx 作为 Web 服务器的网站也越来越多,其中包括新浪博客新浪播客网易新闻等门户网站频道,六间房56.com等视频分享网站,Discuz!官方论坛水木社区等知名论坛,豆瓣YUPOO相册海内SNS迅雷在线等新兴Web 2.0网站。


Nginx 的官方中文维基:http://wiki.nginx.org/NginxChs


在高并发连接的情况下,Nginx是Apache服务器不错的替代品。Nginx同时也可以作为7层负载均衡服务器来使用。根据我的测试结果,Nginx 0.8.15 + PHP 5.2.10 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍。根据我的经验,4GB内存的服务器+Apache(prefork模式)一般只能处理3000个并发连接,因为它们将占用3GB以上的内存,还得为系统 预留1GB的内存。我曾经就有两台Apache服务器,因为在配置文件中设置的MaxClients为4000,当Apache并发连接数达到3800 时,导致服务器内存和Swap空间用满而崩溃。而这台 Nginx 0.8.15 + PHP 5.2.10 (FastCGI) 服务器在3万并发连接下,开启的10个Nginx进程消耗150M内存(15M*10=150M),开启的64个php-cgi进程消耗1280M内存 (20M*64=1280M),加上系统自身消耗的内存,总共消耗不到2GB内存。如果服务器内存较小,完全可以只开启25个php-cgi进程,这样 php-cgi消耗的总内存数才500M。在3万并发连接下,访问Nginx 0.8.15 + PHP 5.2.10 (FastCGI) 服务器的PHP程序,仍然速度飞快。下图为Nginx的状态监控页面,显示的活动连接数为28457(关于Nginx的监控页配置,会在本文接下来所给出 的Nginx配置文件中写明):
点击在新窗口中浏览此图片我生产环境下的两台Nginx + PHP5(FastCGI)服务器,跑多个一般复杂的纯PHP动态程序,单台Nginx + PHP5(FastCGI)服务器跑PHP动态程序的处理能力已经超过“700次请求/秒”,相当于每天可以承受6000万(700*60*60*24=60480000)的访问量(更多信息见此),而服务器的系统负载也不高:
点击在新窗口中浏览此图片2009年9月3日下午2:30,金山游戏《剑侠情缘网络版叁》临时维护1小时(http://kefu.xoyo.com/gonggao/jx3/2009-09-03/750438.shtml),大量玩家上官网,论坛、评论、客服等动态应用Nginx服务器集群,每台服务器的Nginx活动连接数达到2.8万,这是笔者遇到的Nginx生产环境最高并发值。点击在新窗口中浏览此图片


下面是用100个并发连接分别去压生产环境中同一负载均衡器VIP下、提供相同服务的两台服务器,一台为Nginx,另一台为Apache,Nginx每秒处理的请求数是Apache的两倍多,Nginx服务器的系统负载、CPU使用率远低于Apache:你可以将连接数开到10000~30000,去压Nginx和Apache上的phpinfo.php,这是用浏览器访问Nginx上的 phpinfo.php一切正常,而访问Apache服务器的phpinfo.php,则是该页无法显示。4G内存的服务器,即使再优化,Apache也 很难在“webbench -c 30000 -t 60 http://xxx.xxx.xxx.xxx/phpinfo.php”的压力情况下正常访问,而调整参数优化后的Nginx可以。webbench 下载地址:http://blog.s135.com/post/288/注意:webbench 做压力测试时,该软件自身也会消耗CPU和内存资源,为了测试准确,请将 webbench 安装在别的服务器上。测试结果:##### Nginx + PHP #####

引用

[root@localhost webbench-1.5]# webbench -c 100 -t 30 http://192.168.1.21/phpinfo.php

Webbench - Simple Web Benchmark 1.5

Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.Benchmarking: GET http://192.168.1.21/phpinfo.php

100 clients, running 30 sec.

Speed=102450 pages/min, 16490596 bytes/sec.

Requests: 51225 susceed, 0 failed.

top - 14:06:13 up 27 days,  2:25,  2 users,  load average: 14.57, 9.89, 6.51

Tasks: 287 total,   4 running, 283 sleeping,   0 stopped,   0 zombie

Cpu(s): 49.9% us,  6.7% sy,  0.0% ni, 41.4% id,  1.1% wa,  0.1% hi,  0.8% si

Mem:   6230016k total,  2959468k used,  3270548k free,   635992k buffers

Swap:  2031608k total,     3696k used,  2027912k free,  1231444k cached

测试结果:##### Apache + PHP #####

引用

[root@localhost webbench-1.5]# webbench -c 100 -t 30 http://192.168.1.27/phpinfo.php
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://192.168.1.27/phpinfo.php
100 clients, running 30 sec.

Speed=42184 pages/min, 31512914 bytes/sec.
Requests: 21092 susceed, 0 failed.

top - 14:06:20 up 27 days,  2:13,  2 users,  load average: 62.15, 26.36, 13.42
Tasks: 318 total,   7 running, 310 sleeping,   0 stopped,   1 zombie
Cpu(s): 80.4% us, 10.6% sy,  0.0% ni,  7.9% id,  0.1% wa,  0.1% hi,  0.9% si
Mem:   6230016k total,  3075948k used,  3154068k free,   379896k buffers
Swap:  2031608k total,    12592k used,  2019016k free,  1117868k cached

为什么Nginx的性能要比Apache高得多?这得益于Nginx使用了最新的epoll(Linux 2.6内核)和kqueue(freebsd)网络I/O模型,而Apache则使用的是传统的select模型。目前Linux下能够承受高并发访问的 Squid、Memcached都采用的是epoll网络I/O模型。处理大量的连接的读写,Apache所采用的select网络I/O模型非常低效。下面用一个比喻来解析Apache采用的select模型和Nginx采用的epoll模型进行之间的区别:假设你在大学读书,住的宿舍楼有很多间房间,你的朋友要来找你。select版宿管大妈就会带着你的朋友挨个房间去找,直到找到你为止。而epoll版 宿管大妈会先记下每位同学的房间号,你的朋友来时,只需告诉你的朋友你住在哪个房间即可,不用亲自带着你的朋友满大楼找人。如果来了10000个人,都要 找自己住这栋楼的同学时,select版和epoll版宿管大妈,谁的效率更高,不言自明。同理,在高并发服务器中,轮询I/O是最耗时间的操作之 一,select和epoll的性能谁的性能更高,同样十分明了。


安装步骤:
(系统要求:Linux 2.6+ 内核,本文中的Linux操作系统为CentOS 5.3,另在RedHat AS4上也安装成功)一、获取相关开源程序:
1、【适用CentOS操作系统】利用CentOS Linux系统自带的yum命令安装、升级所需的程序库(RedHat等其他Linux发行版可从安装光盘中找到这些程序库的RPM包,进行安装):

[root@localhost ~]# sudo -s
[root@localhost ~]# LANG=C
[root@localhost ~]# 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

2、【适用RedHat操作系统】RedHat等其他Linux发行版可从安装光盘中找到这些程序库的RPM包(事先可通过类似“rpm -qa | grep libjpeg”的命令查看所需的RPM包是否存在,通常是“xxx-devel”不存在,需要安装)。RedHat可以直接利用CentOS的RPM包 安装,以下是RPM包下载网址:
①、RedHat AS4 & CentOS 4
http://mirrors.163.com/centos/4/os/i386/CentOS/RPMS/
http://mirrors.163.com/centos/4/os/x86_64/CentOS/RPMS/

②、RedHat AS5 & CentOS 5
http://mirrors.163.com/centos/5/os/i386/CentOS/
http://mirrors.163.com/centos/5/os/x86_64/CentOS/

③、RPM包搜索网站
http://rpm.pbone.net/
http://www.rpmfind.net/

④、RedHat AS4 系统环境,通常情况下缺少的支持包安装:
Ⅰ、i386 系统

[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/i386/libjpeg-devel-6b-33.i386.rpm
[root@localhost opt]# rpm -ivh libjpeg-devel-6b-33.i386.rpm
[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/i386/freetype-devel-2.1.9-1.i386.rpm
[root@localhost opt]# rpm -ivh freetype-devel-2.1.9-1.i386.rpm
[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/i386/libpng-devel-1.2.7-1.i386.rpm
[root@localhost opt]# rpm -ivh libpng-devel-1.2.7-1.i386.rpm

Ⅱ、x86_64 系统

[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/x86_64/libjpeg-devel-6b-33.x86_64.rpm
[root@localhost opt]# rpm -ivh libjpeg-devel-6b-33.x86_64.rpm
[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/x86_64/freetype-devel-2.1.9-1.x86_64.rpm
[root@localhost opt]# rpm -ivh freetype-devel-2.1.9-1.x86_64.rpm
[root@localhost opt]# wget http://blog.s135.com/soft/linux/nginx_php/rpm/x86_64/libpng-devel-1.2.7-1.x86_64.rpm
[root@localhost opt]# rpm -ivh libpng-devel-1.2.7-1.x86_64.rpm

如果[rpm -ivh freetype-devel-2.1.9-1.x86_64.rpm]出错请执行[rpm -ivh –force –nodeps freetype-devel-2.1.9-1.x86_64.rpm]
如果[rpm -ivh libpng-devel-1.2.7-1.x86_64.rpm]出错请执行[rpm -ivh –force –nodeps libpng-devel-1.2.7-1.x86_64.rpm]

3、【适用CentOS、RedHat及其它Linux操作系统】下载程序源码包:
本文中提到的所有开源软件为截止到2009年09月18日的最新稳定版。
①、从软件的官方网站下载:

[root@localhost opt]# mkdir -p /opt/server
[root@localhost opt]# cd /opt/server
[root@localhost server]# wget http://sysoev.ru/nginx/nginx-0.8.15.tar.gz
[root@localhost server]# wget http://www.php.net/get/php-5.2.10.tar.gz/from/this/mirror
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/phpfpm/php-5.2.10-fpm-0.5.11.diff.gz
[root@localhost server]# wget http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-5.1.38.tar.gz/from/http://mysql.he.net/
[root@localhost server]# wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.tar.gz
[root@localhost server]# wget http://downloads.sourceforge.net/mcrypt/libmcrypt-2.5.8.tar.gz?modtime=1171868460&big_mirror=0
[root@localhost server]# wget http://downloads.sourceforge.net/mcrypt/mcrypt-2.6.8.tar.gz?modtime=1194463373&big_mirror=0
[root@localhost server]# wget http://pecl.php.net/get/memcache-2.2.5.tgz
[root@localhost server]# wget http://downloads.sourceforge.net/mhash/mhash-0.9.9.9.tar.gz?modtime=1175740843&big_mirror=0
[root@localhost server]# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.9.tar.gz
[root@localhost server]# wget http://bart.eaccelerator.net/source/0.9.5.3/eaccelerator-0.9.5.3.tar.bz2
[root@localhost server]# wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/imagick/ImageMagick.tar.gz
[root@localhost server]# wget http://pecl.php.net/get/imagick-2.2.2.tgz

②、从blog.s135.com下载(比较稳定,只允许在本站,或者在Linux/Unix下通过Wget、Curl等命令下载以下软件):

[root@localhost server]# mkdir -p /opt/server
[root@localhost server]# cd /opt/server
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/nginx/nginx-0.8.15.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/php/php-5.2.10.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/phpfpm/php-5.2.10-fpm-0.5.11.diff.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/mysql/mysql-5.1.38.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/libiconv/libiconv-1.13.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/mcrypt/libmcrypt-2.5.8.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/mcrypt/mcrypt-2.6.8.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/memcache/memcache-2.2.5.tgz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/mhash/mhash-0.9.9.9.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/pcre/pcre-7.9.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/eaccelerator/eaccelerator-0.9.5.3.tar.bz2
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/pdo/PDO_MYSQL-1.0.2.tgz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/imagick/ImageMagick.tar.gz
[root@localhost server]# wget http://blog.s135.com/soft/linux/nginx_php/imagick/imagick-2.2.2.tgz

二、安装PHP 5.2.10(FastCGI模式)
1、编译安装PHP 5.2.10所需的支持库:

[root@localhost server]# tar zxvf libiconv-1.13.tar.gz
[root@localhost libiconv-1.13]# cd libiconv-1.13/
[root@localhost libiconv-1.13]# ./configure --prefix=/usr/local
[root@localhost libiconv-1.13]# make
[root@localhost libiconv-1.13]# make install
[root@localhost libiconv-1.13]# cd ../

[root@localhost server]# tar zxvf libmcrypt-2.5.8.tar.gz
[root@localhost server]# cd libmcrypt-2.5.8/
[root@localhost libmcrypt-2.5.8]# ./configure
[root@localhost libmcrypt-2.5.8]# make
[root@localhost libmcrypt-2.5.8]# make install
[root@localhost libmcrypt-2.5.8]# /sbin/ldconfig
[root@localhost libltdl]# cd libltdl/
[root@localhost libltdl]# ./configure --enable-ltdl-install
[root@localhost libltdl]# make
[root@localhost libltdl]# make install
[root@localhost libltdl]# cd ../../

[root@localhost server]# tar zxvf mhash-0.9.9.9.tar.gz
[root@localhost server]# cd mhash-0.9.9.9/
[root@localhost mhash-0.9.9.9]# ./configure
[root@localhost mhash-0.9.9.9]# make
[root@localhost mhash-0.9.9.9]# make install
[root@localhost mhash-0.9.9.9]# cd ../

[root@localhost server]# ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
[root@localhost server]# ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
[root@localhost server]# ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
[root@localhost server]# ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
[root@localhost server]# ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
[root@localhost server]# ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
[root@localhost server]# ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
[root@localhost server]# ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
[root@localhost server]# ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1

[root@localhost server]# tar zxvf mcrypt-2.6.8.tar.gz
[root@localhost server]# cd mcrypt-2.6.8/
[root@localhost mcrypt-2.6.8]# /sbin/ldconfig
[root@localhost mcrypt-2.6.8]# ./configure
[root@localhost mcrypt-2.6.8]# make
[root@localhost mcrypt-2.6.8]# make install
[root@localhost mcrypt-2.6.8]# cd ../

如果mcrypt-2.6.8安装configure时[报错:configure: error: *** libmcrypt was not found]
[解决方法:ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config]
[如果不行,再前面执行:yum -y install libtool-ltdl
yum -y install libtool-ltdl-devel
ln -sf /usr/lib64/libltdl.a /usr/local/lib/libltdl.a]


2、编译安装MySQL 5.1.38

[root@localhost server]# /usr/sbin/groupadd mysql
[root@localhost server]# /usr/sbin/useradd -g mysql mysql
[root@localhost server]# tar zxvf mysql-5.1.38.tar.gz
[root@localhost mysql-5.1.38]# cd mysql-5.1.38/
[root@localhost mysql-5.1.38]# ./configure --prefix=/usr/local/mysql/ --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile --with-plugins=innobase
[root@localhost mysql-5.1.38]# make && make install
[root@localhost mysql-5.1.38]# chmod +w /usr/local/mysql
[root@localhost mysql-5.1.38]# chown -R mysql:mysql /usr/local/mysql
[root@localhost mysql-5.1.38]# cd ../

附:以下为附加步骤,如果你想在这台服务器上运行MySQL数据库,则执行以下两步。如果你只是希望让PHP支持MySQL扩展库,能够连接其他服务器上的MySQL数据库,那么,以下两步无需执行。①、创建MySQL数据库存放目录

[root@localhost server]# mkdir -p /data/mysql/3306/data/
[root@localhost server]# chown -R mysql:mysql /data/mysql/

②、以mysql用户帐号的身份建立数据表:

[root@localhost server]# /usr/local/mysql/bin/mysql_install_db --basedir=/usr/local/mysql --datadir=/data/mysql/3306/data --user=mysql

③、创建my.cnf配置文件:

[root@localhost server]# vi /data/mysql/3306/my.cnf

输入以下内容:

引用

[client]
default-character-set = utf8
port    = 3306
socket  = /tmp/mysql.sock

[mysql]
prompt="(\u:blog.s135.com:)[\d]>"
no-auto-rehash

[mysqld]
#default-character-set = utf8
user    = mysql
port    = 3306
socket  = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql/3306/data
open_files_limit    = 10240
back_log = 600
max_connections = 3000
max_connect_errors = 6000
table_cache = 614
external-locking = FALSE
max_allowed_packet = 32M
sort_buffer_size = 2M
join_buffer_size = 2M
thread_cache_size = 300
thread_concurrency = 8
query_cache_size = 32M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
default-storage-engine = MyISAM
default_table_type = MyISAM
thread_stack = 192K
transaction_isolation = READ-COMMITTED
tmp_table_size = 246M
max_heap_table_size = 246M
long_query_time = 1
log_long_format
log-bin = /data/mysql/3306/binlog
binlog_cache_size = 4M
binlog_format = MIXED
max_binlog_cache_size = 8M
max_binlog_size = 512M
expire_logs_days = 7
key_buffer_size = 256M
read_buffer_size = 1M
read_rnd_buffer_size = 16M
bulk_insert_buffer_size = 64M
myisam_sort_buffer_size = 128M
myisam_max_sort_file_size = 10G
myisam_max_extra_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover

skip-name-resolve
master-connect-retry = 10
slave-skip-errors = 1032,1062,126,1114,1146,1048,1396

server-id = 1

innodb_additional_mem_pool_size = 16M
innodb_buffer_pool_size = 2048M
innodb_data_file_path = ibdata1:1024M:autoextend
innodb_file_io_threads = 4
innodb_thread_concurrency = 8
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 16M
innodb_log_file_size = 128M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
innodb_file_per_table = 0
[mysqldump]
quick
max_allowed_packet = 32M

④、创建管理MySQL数据库的shell脚本:

[root@localhost server]# vi /data/mysql/3306/mysql

输入以下内容(这里的用户名admin和密码12345678接下来的步骤会创建):

#!/bin/sh

mysql_port=3306
mysql_username="admin"
mysql_password="12345678"

function_start_mysql()
{
    printf "Starting MySQL...\n"
    /bin/sh /usr/local/mysql/bin/mysqld_safe --defaults-file=/data/mysql/${mysql_port}/my.cnf 2>&1 > /dev/null &
}

function_stop_mysql()
{
    printf "Stoping MySQL...\n"
    /usr/local/mysql/bin/mysqladmin -u ${mysql_username} -p${mysql_password} -S /tmp/mysql.sock shutdown
}

function_restart_mysql()
{
    printf "Restarting MySQL...\n"
    function_stop_mysql
    sleep 5
    function_start_mysql
}

function_kill_mysql()
{
    kill -9 $(ps -ef | grep 'bin/mysqld_safe' | grep ${mysql_port} | awk '{printf $2}')
    kill -9 $(ps -ef | grep 'libexec/mysqld' | grep ${mysql_port} | awk '{printf $2}')
}

if [ "$1" = "start" ]; then
    function_start_mysql
elif [ "$1" = "stop" ]; then
    function_stop_mysql
elif [ "$1" = "restart" ]; then
function_restart_mysql
elif [ "$1" = "kill" ]; then
function_kill_mysql
else
    printf "Usage: /data/mysql/${mysql_port}/mysql {start|stop|restart|kill}\n"
fi

⑤、赋予shell脚本可执行权限:

[root@localhost server]# chmod +x /data/mysql/3306/mysql

⑥、启动MySQL:

[root@localhost server]# /data/mysql/3306/mysql start

这里要还需要设置MySQL的root用户密码:/usr/local/mysql/bin/mysqladmin -u root password “123456”
⑦、通过命令行登录管理MySQL服务器(提示输入密码时输入:123456 回车):

[root@localhost server]# /usr/local/mysql/bin/mysql -u root -p -S /tmp/mysql.sock

⑧、输入以下SQL语句,创建一个具有root权限的用户(admin)和密码(12345678):

mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY '12345678';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'127.0.0.1' IDENTIFIED BY '12345678';

⑨、(可选)停止MySQL:

[root@localhost server]# /data/mysql/3306/mysql stop

3、编译安装PHP(FastCGI模式)

[root@localhost server]# tar zxvf php-5.2.10.tar.gz
[root@localhost server]# gzip -cd php-5.2.10-fpm-0.5.11.diff.gz | patch -d php-5.2.10 -p1
[root@localhost server]# cd php-5.2.10/
[root@localhost php-5.2.10]# ./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap --without-pear
[root@localhost php-5.2.10]# make ZEND_EXTRA_LIBS='-liconv'
[root@localhost php-5.2.10]# make install
[root@localhost php-5.2.10]# cp php.ini-dist /usr/local/php/etc/php.ini
[root@localhost php-5.2.10]# cd ../
[root@localhost server]# curl http://pear.php.net/go-pear | /usr/local/php/bin/php

如果configure报错[make: *** [sapi/cgi/php-cgi] Error 1]
解决方法:[yum install libtool-ltdl.x86_64 libtool-ltdl-devel.x86_64]
[报错:gcc: /usr/lib64/libfreetype.so: No such file or directory
make: *** [sapi/cgi/php-cgi] Error 1]
解决方法:[ln -s /usr/lib64/libfreetype.so.6.3.10 /usr/lib64/libfreetype.so]


4、编译安装PHP5扩展模块

[root@localhost server]# tar zxvf memcache-2.2.5.tgz
[root@localhost server]# cd memcache-2.2.5/
[root@localhost memcache-2.2.5]# /usr/local/php/bin/phpize
[root@localhost memcache-2.2.5]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@localhost memcache-2.2.5]# make
[root@localhost memcache-2.2.5]# make install
[root@localhost memcache-2.2.5]# cd ../

[root@localhost server]# tar jxvf eaccelerator-0.9.5.3.tar.bz2
[root@localhost server]# cd eaccelerator-0.9.5.3/
[root@localhost eaccelerator-0.9.5.3]# /usr/local/php/bin/phpize
[root@localhost eaccelerator-0.9.5.3]# ./configure --enable-eaccelerator=shared --with-php-config=/usr/local/php/bin/php-config
[root@localhost eaccelerator-0.9.5.3]# make
[root@localhost eaccelerator-0.9.5.3]# make install
[root@localhost eaccelerator-0.9.5.3]# cd ../

[root@localhost server]# tar zxvf PDO_MYSQL-1.0.2.tgz
[root@localhost server]# cd PDO_MYSQL-1.0.2/
[root@localhost PDO_MYSQL-1.0.2]# /usr/local/php/bin/phpize
[root@localhost PDO_MYSQL-1.0.2]# ./configure --with-php-config=/usr/local/php/bin/php-config --with-pdo-mysql=/usr/local/mysql
[root@localhost PDO_MYSQL-1.0.2]# make
[root@localhost PDO_MYSQL-1.0.2]# make install
[root@localhost PDO_MYSQL-1.0.2]# cd ../

[root@localhost server]# tar zxvf ImageMagick.tar.gz
[root@localhost server]# cd ImageMagick-6.5.1-2/
[root@localhost ImageMagick-6.5.1-2]# ./configure
[root@localhost ImageMagick-6.5.1-2]# make
[root@localhost ImageMagick-6.5.1-2]# make install
[root@localhost ImageMagick-6.5.1-2]# cd ../

[root@localhost server]# tar zxvf imagick-2.2.2.tgz
[root@localhost server]# cd imagick-2.2.2/
[root@localhost imagick-2.2.2]# /usr/local/php/bin/phpize
[root@localhost imagick-2.2.2]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@localhost imagick-2.2.2]# make
[root@localhost imagick-2.2.2]# make install
[root@localhost imagick-2.2.2]# cd ../

5、修改php.ini文件
手工修改:查找/usr/local/php/etc/php.ini中的extension_dir = “./”
修改为extension_dir = “/usr/local/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

自动修改:若嫌手工修改麻烦,可执行以下shell命令,自动完成对php.ini文件的修改:

[root@localhost server]# sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"\nextension = "memcache.so"\nextension = "pdo_mysql.so"\nextension = "imagick.so"\n#' /usr/local/php/etc/php.ini
[root@localhost server]# sed -i 's#output_buffering = Off#output_buffering = On#' /usr/local/php/etc/php.ini
[root@localhost server]# sed -i "s#; always_populate_raw_post_data = On#always_populate_raw_post_data = On#g" /usr/local/php/etc/php.ini

6、配置eAccelerator加速PHP:

[root@localhost server]# mkdir -p /usr/local/eaccelerator_cache
[root@localhost server]# vi /usr/local/php/etc/php.ini

按shift+g键跳到配置文件的最末尾,加上以下配置信息:

[eaccelerator]
zend_extension="/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/usr/local/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"

7、创建www用户和组,以及供blog.s135.com和www.s135.com两个虚拟主机使用的目录:

[root@localhost server]# /usr/sbin/groupadd www
[root@localhost server]# /usr/sbin/useradd -g www www
[root@localhost server]# mkdir -p /data/htdocs/blog
[root@localhost server]# chmod +w /data/htdocs/blog
[root@localhost server]# chown -R www:www /data/htdocs/blog
[root@localhost server]# mkdir -p /data/htdocs/www
[root@localhost server]# chmod +w /data/htdocs/www
[root@localhost server]# chown -R www:www /data/htdocs/www

8、创建php-fpm配置文件(php-fpm是为PHP打的一个FastCGI管理补丁,可以平滑变更php.ini配置而无需重启php-cgi):
在/usr/local/php/etc/目录中创建php-fpm.conf文件:

[root@localhost server]# rm -f /usr/local/php/etc/php-fpm.conf
[root@localhost server]# vi /usr/local/php/etc/php-fpm.conf

输入以下内容[内容可能copy不完整,可以直接下载php-fpm.conf](如果您安装 Nginx + PHP 用于程序调试,请将以下的0改为1,以便显示PHP错误信息,否则,Nginx 会报状态为500的空白错误页):

< ?xml version="1.0" ?>All relative paths in this config are relative to php's install prefix
Pid file/usr/local/php/logs/php-fpm.pidError log file/usr/local/php/logs/php-fpm.logLog levelnoticeWhen this amount of php processes exited with SIGSEGV or SIGBUS ...10... in a less than this interval of time, a graceful restart will be initiated. Useful to work around accidental curruptions in accelerator's shared memory.1mTime limit on waiting child's reaction on signals from master5sSet to 'no' to debug fpmyes
Name of pool. Used in logs and stats.defaultAddress to accept fastcgi requests on. Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket'127.0.0.1:9000Set listen(2) backlog-1Set permissions for unix socket, if one used. In Linux read/write permissions must be set in order to allow connections from web server. Many BSD-derrived systems allow connections regardless of permissions.0666Additional php.ini defines, specific to this pool of workers./usr/sbin/sendmail -t -i1Unix user of processeswwwUnix group of processeswwwProcess manager settingsSets style of controling worker process count. Valid values are 'static' and 'apache-like'staticSets the limit on the number of simultaneous requests that will be served. Equivalent to Apache MaxClients directive. Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi Used with any pm_style.128Settings group for 'apache-like' pm styleSets the number of server processes created on startup. Used only when 'apache-like' pm_style is selected20Sets the desired minimum number of idle server processes. Used only when 'apache-like' pm_style is selected5Sets the desired maximum number of idle server processes. Used only when 'apache-like' pm_style is selected35The timeout (in seconds) for serving a single request after which the worker process will be terminated Should be used when 'max_execution_time' ini option does not stop script execution for some reason '0s' means 'off'0sThe timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file '0s' means 'off'0sThe log file for slow requestslogs/slow.logSet open file desc rlimit51200Set max core size rlimit0Chroot to this directory at the start, absolute pathChdir to this directory at the start, absolute pathRedirect workers' stdout and stderr into main error log. If not set, they will be redirected to /dev/null, according to FastCGI specsyesHow much requests each process should execute before respawn. Useful to work around memory leaks in 3rd party libraries. For endless request processing please specify 0 Equivalent to PHP_FCGI_MAX_REQUESTS500Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect. Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+) Makes sense only with AF_INET listening socket.127.0.0.1Pass environment variables like LD_LIBRARY_PATH All $VARIABLEs are taken from current environment$HOSTNAME/usr/local/bin:/usr/bin:/bin/tmp/tmp/tmp$OSTYPE$MACHTYPE2

9、启动php-cgi进程,监听127.0.0.1的9000端口,进程数为200(如果服务器内存小于3GB,可以只开启64个进程),用户为www:

[root@localhost server]# ulimit -SHn 65535
[root@localhost server]# /usr/local/php/sbin/php-fpm start

注:/usr/local/php/sbin/php-fpm还有其他参数,包 括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件 使用reload。


三、安装Nginx 0.8.15
1、安装Nginx所需的pcre库:

[root@localhost server]# tar zxvf pcre-7.9.tar.gz
[root@localhost server]# cd pcre-7.9/
[root@localhost pcre-7.9]# ./configure
[root@localhost pcre-7.9]# make && make install
[root@localhost pcre-7.9]# cd ../

2、安装Nginx

[root@localhost server]# tar zxvf nginx-0.8.15.tar.gz
[root@localhost server]# cd nginx-0.8.15/
[root@localhost nginx-0.8.15]# ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
[root@localhost nginx-0.8.15]# make && make install
[root@localhost nginx-0.8.15]# cd ../

3、创建Nginx日志目录

[root@localhost server]# mkdir -p /data/logs
[root@localhost server]# chmod +w /data/logs
[root@localhost server]# chown -R www:www /data/logs

4、创建Nginx配置文件
①、在/usr/local/nginx/conf/目录中创建nginx.conf文件:

[root@localhost server]# rm -f /usr/local/nginx/conf/nginx.conf
[root@localhost server]# vi /usr/local/nginx/conf/nginx.conf

输入以下内容:

user  www www;

worker_processes 8;

error_log  /data/logs/nginx_error.log  crit;

pid        /usr/local/nginx/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

events
{
  use epoll;
  worker_connections 65535;
}

http
{
  include       mime.types;
  default_type  application/octet-stream;

  #charset  gb2312;

  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 8m;

  sendfile on;
  tcp_nopush     on;

  keepalive_timeout 60;

  tcp_nodelay on;

  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;

  gzip on;
  gzip_min_length  1k;
  gzip_buffers     4 16k;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_types       text/plain application/x-javascript text/css application/xml;
  gzip_vary on;

  #limit_zone  crawler  $binary_remote_addr  10m;

  server
  {
    listen       80;
    server_name  blog.s135.com;
    index index.html index.htm index.php;
    root  /data/htdocs/blog;

    #limit_conn   crawler  20;    

    location ~ .*.(php|php5)?$
    {
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }

    location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      30d;
    }

    location ~ .*.(js|css)?$
    {
      expires      1h;
    }    

    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" $http_x_forwarded_for';
    access_log  /data/logs/access.log  access;
      }

  server
  {
    listen       80;
    server_name  www.s135.com;
    index index.html index.htm index.php;
    root  /data/htdocs/www;

    location ~ .*.(php|php5)?$
    {
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }

    log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';
    access_log  /data/logs/wwwlogs.log  wwwlogs;
  }

  server
  {
    listen  80;
    server_name  status.blog.s135.com;

    location / {
    stub_status on;
    access_log   off;
    }
  }
}

②、在/usr/local/nginx/conf/目录中创建fcgi.conf文件:

[root@localhost server]# vi /usr/local/nginx/conf/fcgi.conf

输入以下内容:

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;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

5、启动Nginx

[root@localhost server]# ulimit -SHn 65535
[root@localhost server]# /usr/local/nginx/sbin/nginx

四、配置开机自动启动Nginx + PHP

[root@localhost server]# vi /etc/rc.local

在末尾增加以下内容:

ulimit -SHn 65535
/usr/local/php/sbin/php-fpm start
/usr/local/nginx/sbin/nginx

五、优化Linux内核参数

[root@localhost server]# vi /etc/sysctl.conf

在末尾增加以下内容:

# Add
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog =  32768
net.core.somaxconn = 32768

net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216

net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2

net.ipv4.tcp_tw_recycle = 1
#net.ipv4.tcp_tw_len = 1
net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800

#net.ipv4.tcp_fin_timeout = 30
#net.ipv4.tcp_keepalive_time = 120
net.ipv4.ip_local_port_range = 1024  65535

使配置立即生效:

[root@localhost server]# /sbin/sysctl -p

六、在不停止Nginx服务的情况下平滑变更Nginx配置
1、修改/usr/local/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:

[root@localhost server]# /usr/local/nginx/sbin/nginx -t

如果屏幕显示以下两行信息,说明配置文件正确:
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully

2、这时,输入以下命令查看Nginx主进程号:

[root@localhost server]# ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

屏幕显示的即为Nginx主进程号,例如:
6302
这时,执行以下命令即可使修改过的Nginx配置文件生效:

[root@localhost server]# kill -HUP 6302

或者无需这么麻烦,找到Nginx的Pid文件:

[root@localhost server]# kill -HUP `cat /usr/local/nginx/nginx.pid`

七、编写每天定时切割Nginx日志的脚本
1、创建脚本/usr/local/nginx/sbin/cut_nginx_log.sh

[root@localhost server]# vi /usr/local/nginx/sbin/cut_nginx_log.sh
输入以下内容:
#!/bin/bash
# This script run at 00:00

# The Nginx logs path
logs_path="/usr/local/nginx/logs/"

mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/nginx/nginx.pid`

2、设置crontab,每天凌晨00:00切割nginx访问日志

[root@localhost server]# crontab -e

输入以下内容:

00 00 * * * /bin/bash  /usr/local/nginx/sbin/cut_nginx_log.sh

使用Nginx的proxy_cache缓存功能取代Squid[转载]

Nginx从0.7.48版本开始,支持了类似Squid的缓存功能。这个缓存是把URL及相关组合当作Key,用md5编码哈希后保存在硬盘上,所 以它可以支持任意URL链接,同时也支持404/301/302这样的非200状态码。虽然目前官方的Nginx Web缓存服务只能为指定URL或状态码设置过期时间,不支持类似Squid的PURGE指令,手动清除指定缓存页面,但是,通过一个第三方的Nginx 模块,可以清除指定URL的缓存。

Nginx的Web缓存服务主要由proxy_cache相关指令集和fastcgi_cache相关指令集构成,前者用于反向代理时,对后端内容源服务器进行缓存,后者主要用于对FastCGI的动态程序进行缓存。两者的功能基本上一样。

最新的Nginx 0.8.31版本,proxy_cache和fastcgi_cache已经比较完善,加上第三方的ngx_cache_purge模块(用于清除指定 URL的缓存),已经可以完全取代Squid。我们已经在生产环境使用了 Nginx 的 proxy_cache 缓存功能超过两个月,十分稳定,速度不逊于 Squid。

在功能上,Nginx已经具备Squid所拥有的Web缓存加速功能、清除 指定URL缓存的功能。而在性能上,Nginx对多核CPU的利用,胜过Squid不少。另外,在反向代理、负载均衡、健康检查、后端服务器故障转移、 Rewrite重写、易用性上,Nginx也比Squid强大得多。这使得一台Nginx可以同时作为“负载均衡服务器”与“Web缓存服务器”来使用。


1、Nginx 负载均衡与缓存服务器在 Linux 下的编译安装:

[root@localhost server]# ulimit -SHn 65535
[root@localhost server]# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.00.tar.gz
[root@localhost server]# tar zxvf pcre-8.00.tar.gz
[root@localhost pcre-8.00]# cd pcre-8.00/
[root@localhost pcre-8.00]# ./configure
[root@localhost pcre-8.00]# make && make install
[root@localhost pcre-8.00]# cd ../
[root@localhost server]# wget http://labs.frickle.com/files/ngx_cache_purge-1.0.tar.gz
[root@localhost server]# tar zxvf ngx_cache_purge-1.0.tar.gz
[root@localhost server]# wget http://nginx.org/download/nginx-0.8.31.tar.gz
[root@localhost server]# tar zxvf nginx-0.8.31.tar.gz
[root@localhost server]# cd nginx-0.8.31/
[root@localhost nginx-0.8.31]# ./configure --user=www --group=www --add-module=../ngx_cache_purge-1.0 --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
[root@localhost nginx-0.8.31]# make && make install
[root@localhost nginx-0.8.31]# cd ../

2、/usr/local/nginx/conf/nginx.conf 配置文件内容如下:

user  www www;
worker_processes 8;
error_log  /usr/local/webserver/nginx/logs/nginx_error.log  crit;
pid        /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
use epoll;
worker_connections 65535;
}
http
{
include       mime.types;
default_type  application/octet-stream;
charset  utf-8;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 300m;
sendfile on;
tcp_nopush     on;
keepalive_timeout 60;
tcp_nodelay on;
client_body_buffer_size  512k;
proxy_connect_timeout    5;
proxy_read_timeout       60;
proxy_send_timeout       5;
proxy_buffer_size        16k;
proxy_buffers            4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
gzip on;
gzip_min_length  1k;
gzip_buffers     4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types       text/plain application/x-javascript text/css application/xml;
gzip_vary on;
#注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
proxy_temp_path   /data0/proxy_temp_dir;
#设置Web缓存区名称为cache_one,内存缓存空间大小为200MB,1天清理一次缓存,硬盘缓存空间大小为30GB。
proxy_cache_path  /data0/proxy_cache_dir  levels=1:2   keys_zone=cache_one:200m inactive=1d max_size=30g;
upstream backend_server {
server   192.168.8.43:80 weight=1 max_fails=2 fail_timeout=30s;
server   192.168.8.44:80 weight=1 max_fails=2 fail_timeout=30s;
server   192.168.8.45:80 weight=1 max_fails=2 fail_timeout=30s;
}
server
{
listen       80;
server_name  www.yourdomain.com 192.168.8.42;
index index.html index.htm;
root  /data0/htdocs/www;
location /
{
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
#对不同的HTTP状态码设置不同的缓存时间
proxy_cache_valid  200 304 12h;
#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host  $host;
proxy_set_header X-Forwarded-For  $remote_addr;
proxy_pass http://backend_server;
expires      1d;
}
#用于清除缓存,假设一个URL为http://192.168.8.42/test.txt,通过访问http://192.168.8.42/purge/test.txt就可以清除该URL的缓存。
location ~ /purge(/.*)
{
#设置只允许指定的IP或IP段才可以清除URL缓存。
allow            127.0.0.1;
allow            192.168.0.0/16;
deny            all;
proxy_cache_purge    cache_one   $host$1$is_args$args;
}
#扩展名以.php、.jsp、.cgi结尾的动态应用程序不缓存。
location ~ .*\.(php|jsp|cgi)?$
{
proxy_set_header Host  $host;
proxy_set_header X-Forwarded-For  $remote_addr;
proxy_pass http://backend_server;
}
access_log  off;
}
}

3、启动 Nginx:

[root@localhost server]# /usr/local/nginx/sbin/nginx

4、清除指定的URL缓存示例:点击在新窗口中浏览此图片

CentOS 5.3 下快速安装配置 PPTP VPN 服务器

VPN的英文全称是“Virtual Private Network”,翻译过来就是“虚拟专用网络”。顾名思义,虚拟专用网络我们可以把它理解成是虚拟出来的企业内部专线。它可以通过特殊的加密的通讯协议 在连接在Internet上的位于不同地方的两个或多个企业内部网之间建立一条专有的通讯线路,就好比是架设了一条专线一样,但是它并不需要真正的去铺设 光缆之类的物理线路。这就好比去电信局申请专线,但是不用给铺设线路的费用,也不用购买路由器等硬件设备。VPN技术原是路由器具有的重要技术之一,目前 在交换机,防火墙设备或Windows等软件里也都支持VPN功能,一句话,VPN的核心就是在利用公共网络建立虚拟私有网。

虚拟专用网(VPN)被定义为通过一个公用网络(通常是因特网)建立一个临时的、安全的连接,是一条穿过混乱的公用网络的安全、稳定的隧道。虚拟专用网 是对企业内部网的扩展。虚拟专用网可以帮助远程用户、公司分支机构、商业伙伴及供应商同公司的内部网建立可信的安全连接,并保证数据的安全传输。虚拟专用 网可用于不断增长的移动用户的全球因特网接入,以实现安全连接;可用于实现企业网站之间安全通信的虚拟专用线路,用于经济有效地连接到商业伙伴和用户的安 全外联网虚拟专用网。

PPTP 全称为 Point to Point Tunneling Protocol — 点到点隧道协议,是VPN协议中的一种。

一、CentOS 5.3 下 PPTP VPN 服务器安装

1、安装相关软件
32位版:

[root@localhost server]# yum install -y ppp iptables
[root@localhost server]# wget http://poptop.sourceforge.net/yum/stable/packages/pptpd-1.3.4-1.rhel5.1.i386.rpm #或 wget http://www.offar.org/attachments/20100114/pptpd-1.3.4-1.rhel5.1.i386.rpm
[root@localhost server]# rpm -ivh pptpd-1.3.4-1.rhel5.1.i386.rpm

64位版:

[root@localhost server]# yum install -y ppp iptables
[root@localhost server]# wget http://poptop.sourceforge.net/yum/stable/packages/pptpd-1.3.4-1.rhel5.1.x86_64.rpm #或wget ttp://www.offar.org/attachments/20100114/pptpd-1.3.4-1.rhel5.1.x86_64.rpm
[root@localhost server]# rpm -ivh pptpd-1.3.4-1.rhel5.1.x86_64.rpm

2、配置文件编写
①、配置文件/etc/ppp/options.pptpd

[root@localhost server]# mv /etc/ppp/options.pptpd /etc/ppp/options.pptpd.bak
[root@localhost server]# vi /etc/ppp/options.pptpd

输入以下内容:

name pptpd
refuse-pap
refuse-chap
refuse-mschap
require-mschap-v2
require-mppe-128
proxyarp
lock
nobsdcomp
novj
novjccomp
nologfd
ms-dns 208.67.222.222
ms-dns 208.67.220.220

②、配置文件/etc/ppp/chap-secrets

[root@localhost server]# mv /etc/ppp/chap-secrets /etc/ppp/chap-secrets.bak
[root@localhost server]# vi /etc/ppp/chap-secrets

输入以下内容

# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
myusername pptpd mypassword *

注:这里的myusername和mypassword即为PPTP VPN的登录用户名和密码


③、配置文件/etc/pptpd.conf

[root@localhost server]# mv /etc/pptpd.conf /etc/pptpd.conf.bak
[root@localhost server]# vi /etc/pptpd.conf

输入以下内容:

option /etc/ppp/options.pptpd
logwtmp
localip 192.168.9.1
remoteip 192.168.9.11-30

注:为拨入VPN的用户动态分配192.168.9.11~192.168.9.30之间的IP


④、配置文件/etc/sysctl.conf

[root@localhost server]# vi /etc/sysctl.conf

修改以下内容:

net.ipv4.ip_forward = 1

保存、退出后执行:

[root@localhost server]# /sbin/sysctl -p

3、启动PPTP VPN 服务器端:

[root@localhost server]# /sbin/service pptpd start

4、启动iptables:

[root@localhost server]# /sbin/service iptables start
[root@localhost server]# /sbin/iptables -t nat -A POSTROUTING -o eth0 -s 192.168.9.0/24 -j MASQUERADE

Linux操作系统修改时区的方法

Local vs. UTC
首先重要的问题是你使用utc还是local time.
UTC(Universal Time Coordinated)=GMT(Greenwich Mean Time)
Local time 是你手表上的时间
传统的POSIX计算机(Solaris,bsd,unix)使用UTC格式
linux可以处理UTC时间和蹩脚的Windows所使用的local time
到底是使用UTC还是local time可以这样来确定:
如果机器上同时安装有Linux和Windows,建议使用local time
如果机器上只安装有Linux,建议使用utc
确定后编辑/etc/sysconfig/clock, UTC=0 是local time; UTC=1 是UTC(GMT)
确定timezone
运行tzselect,回答问题后会告诉你时区的名称,比如”Asia/Shanghai”,把他记下来(后面我用$timezone代替)
设定timezone
# cp /usr/share/zoneinfo/$timezone /etc/localtime
重新启动或者运行时钟设置脚本使之发生作用
版本差异
由于发行版的差异,以上文件位置可能不同。
一般设置时钟所使用的启动脚本为/etc/rc.d/init.d/setclock
redhat是在/etc/rc.d/rc.sysinit中设置时钟,所以一般要重新启动。

Nginx 500的一种情况

如果您安装 Nginx + PHP 用于程序调试,请将以下的<value name=”display_errors”>0</value>改为<value name=”display_errors”>1</value>,以便显示PHP错误信息,否则,Nginx 会报状态为500的空白错误页

vsftpd限制虚拟用户在根目录

在/etc/vsftpd/vsftpd.conf

加入

chroot_local_user=YES

一,在配置文件中增加以下选项
chroot_local_user=NO
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list
然后,在/etc/vsftpd.chroot_list文件中加入虚拟用户名xiaotong和xiaowang。
第二种做法,在配置文件中修改chroot_local_user=YES。
经过修改后,虚拟用户登录后其根目录就限制在/home/vsftpdguest下,无法访问其他目录。