데이터 베이스 MySQL 튜토리얼 MySQL备份和同步时使用LVM

MySQL备份和同步时使用LVM

Jun 07, 2016 pm 03:27 PM
lvm mysql 작가 사용 동기식 지원

原文作者: Peter Zaitsev 原文来源: http://www.mysqlperformanceblog.com/2006/08/21/using-lvm-for-mysql-backup-and-replication-setup 译者:叶金荣(Email: If someone asks me about MySQL Backup advice my first question would be if they have L

原文作者: Peter Zaitsev
原文来源: http://www.mysqlperformanceblog.com/2006/08/21/using-lvm-for-mysql-backup-and-replication-setup
译者:叶金荣(Email:MySQL备份和同步时使用LVM

If someone asks me about MySQL Backup advice my first question would be if they have LVM installed or have some systems with similar features set for other operation systems. Veritas File System can do it for Solaris. Most SAN systems would work as well.

如果有人问我关于MySQL备份的建议,我会先问操作系统是否安装了LVM或者其他相似功能的软件。Solaris下的Veritas文件系统也可以做到同样的功能。大多数SAN系统也可以。

What is really needed is ability to create atomic snapshot of the volume, which can be later mounted same as original file system

 

Why snapshot based MySQL backups are great ?

为什么基于MySQL快照的备份很好?

There are number of reasons:

原因如下几点:

Almost Hot backup In most cases you can perform this type of backup while your application is running. No need to shut down server, make it read only or anything like it.

几乎是热备 在大多数情况下,可以在应用程序仍在运行的时候执行备份。无需关机,只需设置为只读或者类似只读的限制。

Support for all local disk based storage engines It works with MyISAM and Innodb and BDB, It also should work with Solid, PrimeXT and Falcon storage engines.

支持所有基于本地磁盘的存储引擎 它支持MyISAM, Innodb, BDB,还支持 Solid, PrimeXT 和 Falcon。

Fast Backup You simply do file copy in the binary form so it is hard to beat in speed.

快速备份 只需拷贝二进制格式的文件,在速度方面无以匹敌。

Low Overhead It is simply file copy so overhead to the server is minimal.

低开销 只是文件拷贝,因此对服务器的开销很细微。

Easy to Integrate Do you want to compress backup ? Backup it to tape, FTP or any network backup software - it is easy as you just need to copy files.

容易保持完整性 想要压缩备份文件吗?把它们备份到磁带上,FTP或者网络备份软件 -- 十分简单,因为只需要拷贝文件即可。

Fast Recovery Recovery time is as fast as putting data back and standard MySQL crash recovery, and it can be reduced even further. More on this later.

快速恢复 恢复的时间和标准的MySQL崩溃恢复或数据拷贝回去那么快,甚至可能更快,将来会更快。

Free No extra commercial tools as Innodb Hot Backup are required to perform backup.

免费 无需额外的商业软件,只需Innodb热备工具来执行备份。

Are there any downsides ?

有什么缺点吗?

Need to have snapshot campatibility - this is obvious one.

需要兼容快照 -- 这是明显的。

May need root access In some organizations DBA and System Administrator are different people from different departmnents which might not like to trade access rights between each other.

需要超级用户(root) 在某些组织,DBA和系统管理员来自不同部门不同的人,因此权限各不一样。

Hard to predict downtime I mentioned this solution is often hot backup, but bad thing it is hard to estimate when it is hot and when it is not - FLUSH TABLES WITH READ LOCK may take quite a while to complete on systems with long queries.

停工时间无法预计 我提到的这个方法通常指热备,但是谁也无法预料到底是不是热备 -- FLUSH TABLES WITH READ LOCK 可能会需要执行很长时间才能完成。

Problems with data on multiple volumes If you have logs on separate devices or just your database spanning across multiple volumes you will be in trouble as you will not get consistent snapshot across all the database. Some systems may be able to do atomic snapshot of many volumes.

多卷上的数据问题 如果你把日志放在独立的设备上或者你的数据库分布在多个卷上,这就比较麻烦了,因为无法得到全部数据库的一致性快照。不过有些系统可能能自动做到多卷快照。

Lets speak a bit about how LVM and snapshotting in general works. Really there are different implementations but the sake of them is to provide you with volume which consistently matches state of the volume at the time storage is created. In LVM it is implementeed as copy on write. Special storage area allocated on device where old version of changed pages are stored. You can think about it as about simplified form of versioning like in Innodb if it is closer to you. In other cases snapshot may be implemented by tripple-mirroring. Ie you have RAID1 volume but there are 3 copies of data rather than 2. So you can move one devices out of mirror and use it as snapshot while still having your data safe and secure.

现在讲讲LVM和通常情况下的快照。确实,它们的实现的方式不同,但是目的都是让卷和存储卷创建的数据保持一致。LVM是边写边读。设备中专门分配了一个专用的区域用于保存老版本的内存页变化情况。你可以把它想象成为一个简单的版本管理形式,就像Innodb。另一方面,快照实现的方式就像三重镜像。如果你有RAID1卷,不过数据拷贝的分数是3而不是2。因此可以把一个设备从镜像中去掉,把它作为数据快照,并且还能保持数据安全。

There are two types of snapshots - some of them are read-only while others can be read-write. read-only snapshots may sound good enough as you're only going to read data anyway, but in reality read-write snapshots have number of benefits. First no extra handling is needed for journaling file sytems - you can simply do journal recovery on snapshot. With read-only snapshot you need to make sure filesystem synchronizes device before snapshot is taken so no journal replay is needed.

快照有2种方式 -- 一种是只读另一种是可读写。如果你只须拷贝数据,那么只读快照看起来不错,不过可读写快照则有好几个优点。首先是无需额外处理日至文件系统 -- 你可以快照上简单地实现日志恢复。只读快照则必须保证文件系统在开始快照之前就得和设备同步,因此需要日志重现。

The other benefit of read-write snapshot is you can actually start MySQL Server on it and perform recovery, check tables or do whatever else you might need to do to ensure your backup is consistent. Backing up database which was already corrupted is very nasty problem you want to avoid.

可读写快照的另一个好处是可以启动MySQL服务器,执行恢复、检察数据表或者其他任何要保证备份一致性所需的操作。必须避免备份已经损坏的数据库。

Let's now see what exactly you need to do to perform backup of MySQL Database (or create slave) using LVM2 on Linux.

现在让我们来看看Linux上用LVM2备份MySQL数据库(或者它的slave)所需执行的操作:

1) Connect to MySQL and run FLUSH TABLES WITH READ LOCK
Note - this command may take a while to complete if you have long running queries. The catch here is FLUSH TABLES WITH READ LOCK actually waits for all statements to complete, even selects. So be careful if you have any long running queries. If you're using only Innodb tables and do not need to synchronize binary log position with backup you can skip this step.

1) 连接到MySQL上,运行 FLUSH TABLES WITH READ LOCK
注意 -- 如果你当前正在执行一个较长时间的查询,那么这个命令可能需要较长时间才能完成。在这里 FLUSH TABLES WITH READ LOCK 需要捕获所有的语句都完成了,甚至是 SELECT。因此如果有较长时间的查询时要小心。如果你只使用到Innodb表,就无需同步二进制日志可直接略过这个步骤。

2) While holding connection open run: lvcreate -L16G -s -n dbbackup /dev/Main/Data - This will create snapshot named dbbackup for Logical Volume Main/Data . You should specify enough of undo space to hold modifications during backup process - I've specified 16GB in this case. If your undo size is not large enough snapshot will get invalidated and backup will be aborted.

2) 保持连接,运行 lvcreate -L16G -s -n dbbackup /dev/Main/Data -- 它会创建本地卷 Main/Data 的快照,命名为 dbbackup。备份过程中务必指定足够大的撤销空间用于保存发生变化的东西 -- 我指定了16GB。如果撤销空间不够大,快照就会无效并且备份就终止了。

Sometimes you might run into the errors on this step, The most common one I've resently seen is: snapshot: Required device-mapper target(s) not detected in your kernel - This means snapshot module is not loaded in your kernel by default and you need to load it, which is done by running modprobe dm-snapshot

在这个步骤中,你有时候会碰到错误,最近我经常碰到的一个是:snapshot: Required device-mapper target(s) not detected in your kernel -- 意思是内核默认没有加载快照模块,需要你自己加载,运行命令 modprobe dm-snapshot 即可。

3) Now you have created logical volume and can unlock the tables, but before that you should probably record binary log position which is done by running SHOW MASTER STATUS - This is binary log position you'll need to point your MySQL Slaves created from this snapshot.

 

3) 现在已经创建完本地逻辑卷,可以释放表锁了,不过在这之前,需要记录一下二进制日志的位置,运行 SHOW MASTER STATUS 可以看到 -- 这个位置在MySQL slave上创建快照时需要用到。。

 

4) Snapshot created, now you want to let MySQL Server to continue, which is done by running UNLOCK TABLES or simply closing connection.

4) 快照创建完毕,运行 UNLOCK TABLES 释放锁或者关闭连接,让MySQL服务器继续运行。

5) Mount backup Filesystem: mount /dev/Main/dbbackup /mnt/backup

5) 挂载备份文件系统:mount /dev/Main/dbbackup /mnt/backup

6) Copy data to backup. Normally you can skip slow query logs and error log while taking backup. You also can skip most of binary logs - however if some of your slaves are far behind you might want to keep some of last binary logs just in case, or you can assume in case of recovery from the backup you will need to restore slaves as well and skip binary logs in your backup process.

6) 拷贝备份数据。通常备份时可以略过慢查询日志和错误日志。也可以略过大部分的二进制日志 -- 然而如果有些slave远远落后于master的话,就必须保留所需的二进制日志了,或者你可以假设这种情况下在slave上从备份上恢复数据也可以忽略掉二进制日志。

7) Unmount filesystem umount /mnt/backup

7) 卸载文件系统:umount /mnt/backup

8) Remove snapshot: lvremove -f /dev/Main/dbbackup

8) 删除快照:lvremove -f /dev/Main/dbbackup

If you want to create slave based on such snapshot you need to perform couple of more simple steps

如果你想创建基于slave的快照,就需要多做2个步骤。

9) Extract/Copy database to the slave database directory.

9) 提取/拷贝数据库到slave的数据库目录下。

10) Start MySQL Server. Wait for it to perform recovery.

10) 启动MySQL服务器,等待执行恢复。

11) Use CHANGE MASTER TO to point slave to saved binary log position:

11) 用 CHANGE MASTER TO 告诉slave要保存的二进制日志位置:

PLAIN TEXT
SQL:

<span>CHANGE</span>
master
<span>TO</span>
master_host=<span>"master"</span>, master_user=<span>"user"</span>, master_password=<span>"password"</span>, master_log_file=<span>"host-bin.000335"</span>, master_log_pos=<span>401934686</span>;
로그인 후 복사

12) Run SLAVE START to restart replication.

12) 运行 SLAVE START 重启复制。

With slightly modified process you can clone slaves from the slaves without stopping them - you just need to use SHOW SLAVE STATUS instead of SHOW MASTER STATUS to find out appropriate binary log position. Be careful however - cloning slave from the slave also clones inconsistences in data which slave could have accomulated - especially if you use slave_skip_errors or sql_slave_skip_counter. Cloning master you're starting from consistent copy.

使用稍微修改过的进程,就能无需停止slave的情况下克隆它 -- 运行 SHOW SLAVE STATUS 而不是 SHOW MASTER STATUS,找出合适的二进制日志位置。不过要小心 -- 克隆slave的时候也会把它积累的不一致的数据也克隆了 -- 尤其是使用 slave_skip_errorssql_slave_skip_counter时。克隆master就可以拷贝保持一致的数据。

If you're interested in ready script you can try mylvmbackup by Lenz Grimmer

如果你对上面的过程有兴趣,可以试试 Lenz Grimmer 的 mylvmbackup。


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

MySQL에 루트로 로그인 할 수 없습니다 MySQL에 루트로 로그인 할 수 없습니다 Apr 08, 2025 pm 04:54 PM

Root로 MySQL에 로그인 할 수없는 주된 이유는 권한 문제, 구성 파일 오류, 암호 일관성이 없음, 소켓 파일 문제 또는 방화벽 차단입니다. 솔루션에는 다음이 포함됩니다. 구성 파일의 BAND-ADDRESS 매개 변수가 올바르게 구성되어 있는지 확인하십시오. 루트 사용자 권한이 수정 또는 삭제되어 재설정되었는지 확인하십시오. 케이스 및 특수 문자를 포함하여 비밀번호가 정확한지 확인하십시오. 소켓 파일 권한 설정 및 경로를 확인하십시오. 방화벽이 MySQL 서버에 연결되는지 확인하십시오.

MySQL 테이블 잠금 테이블 변경 여부 MySQL 테이블 잠금 테이블 변경 여부 Apr 08, 2025 pm 05:06 PM

MySQL이 테이블 구조를 수정하면 메타 데이터 잠금 장치가 일반적으로 사용되므로 테이블을 잠글 수 있습니다. 자물쇠의 영향을 줄이려면 다음과 같은 조치를 취할 수 있습니다. 1. 온라인 DDL과 함께 테이블을 사용할 수 있습니다. 2. 배치에서 복잡한 수정을 수행합니다. 3. 소형 또는 피크 기간 동안 운영됩니다. 4. PT-OSC 도구를 사용하여 더 미세한 제어를 달성하십시오.

MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 Apr 08, 2025 pm 07:12 PM

1. 올바른 색인을 사용하여 스캔 한 데이터의 양을 줄임으로써 데이터 검색 속도를 높이십시오. 테이블 열을 여러 번 찾으면 해당 열에 대한 인덱스를 만듭니다. 귀하 또는 귀하의 앱이 기준에 따라 여러 열에서 데이터가 필요한 경우 복합 인덱스 2를 만듭니다. 2. 선택을 피하십시오 * 필요한 열만 선택하면 모든 원치 않는 열을 선택하면 더 많은 서버 메모리를 선택하면 서버가 높은 부하 또는 주파수 시간으로 서버가 속도가 느려지며, 예를 들어 Creation_at 및 Updated_at 및 Timestamps와 같은 열이 포함되어 있지 않기 때문에 쿼리가 필요하지 않기 때문에 테이블은 선택을 피할 수 없습니다.

MySQL 사용자와 데이터베이스의 관계 MySQL 사용자와 데이터베이스의 관계 Apr 08, 2025 pm 07:15 PM

MySQL 데이터베이스에서 사용자와 데이터베이스 간의 관계는 권한과 테이블로 정의됩니다. 사용자는 데이터베이스에 액세스 할 수있는 사용자 이름과 비밀번호가 있습니다. 권한은 보조금 명령을 통해 부여되며 테이블은 Create Table 명령에 의해 생성됩니다. 사용자와 데이터베이스 간의 관계를 설정하려면 데이터베이스를 작성하고 사용자를 생성 한 다음 권한을 부여해야합니다.

MySQL은 지불해야합니다 MySQL은 지불해야합니다 Apr 08, 2025 pm 05:36 PM

MySQL에는 무료 커뮤니티 버전과 유료 엔터프라이즈 버전이 있습니다. 커뮤니티 버전은 무료로 사용 및 수정할 수 있지만 지원은 제한되어 있으며 안정성이 낮은 응용 프로그램에 적합하며 기술 기능이 강합니다. Enterprise Edition은 안정적이고 신뢰할 수있는 고성능 데이터베이스가 필요하고 지원 비용을 기꺼이 지불하는 응용 프로그램에 대한 포괄적 인 상업적 지원을 제공합니다. 버전을 선택할 때 고려 된 요소에는 응용 프로그램 중요도, 예산 책정 및 기술 기술이 포함됩니다. 완벽한 옵션은없고 가장 적합한 옵션 만 있으므로 특정 상황에 따라 신중하게 선택해야합니다.

Redshift Zero ETL과의 RDS MySQL 통합 Redshift Zero ETL과의 RDS MySQL 통합 Apr 08, 2025 pm 07:06 PM

데이터 통합 ​​단순화 : AmazonRdsMysQL 및 Redshift의 Zero ETL 통합 효율적인 데이터 통합은 데이터 중심 구성의 핵심입니다. 전통적인 ETL (추출, 변환,로드) 프로세스는 특히 데이터베이스 (예 : AmazonRDSMySQL)를 데이터웨어 하우스 (예 : Redshift)와 통합 할 때 복잡하고 시간이 많이 걸립니다. 그러나 AWS는 이러한 상황을 완전히 변경 한 Zero ETL 통합 솔루션을 제공하여 RDSMYSQL에서 Redshift로 데이터 마이그레이션을위한 단순화 된 거의 실시간 솔루션을 제공합니다. 이 기사는 RDSMYSQL ZERL ETL 통합으로 Redshift와 함께 작동하여 데이터 엔지니어 및 개발자에게 제공하는 장점과 장점을 설명합니다.

MySQL은 Android에서 실행할 수 있습니다 MySQL은 Android에서 실행할 수 있습니다 Apr 08, 2025 pm 05:03 PM

MySQL은 Android에서 직접 실행할 수는 없지만 다음 방법을 사용하여 간접적으로 구현할 수 있습니다. Android 시스템에 구축 된 Lightweight Database SQLite를 사용하여 별도의 서버가 필요하지 않으며 모바일 장치 애플리케이션에 매우 적합한 작은 리소스 사용량이 있습니다. MySQL 서버에 원격으로 연결하고 데이터 읽기 및 쓰기를 위해 네트워크를 통해 원격 서버의 MySQL 데이터베이스에 연결하지만 강력한 네트워크 종속성, 보안 문제 및 서버 비용과 같은 단점이 있습니다.

고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? 고로드 애플리케이션의 MySQL 성능을 최적화하는 방법은 무엇입니까? Apr 08, 2025 pm 06:03 PM

MySQL 데이터베이스 성능 최적화 안내서 리소스 집약적 응용 프로그램에서 MySQL 데이터베이스는 중요한 역할을 수행하며 대규모 트랜잭션 관리를 담당합니다. 그러나 응용 프로그램 규모가 확장됨에 따라 데이터베이스 성능 병목 현상은 종종 제약이됩니다. 이 기사는 일련의 효과적인 MySQL 성능 최적화 전략을 탐색하여 응용 프로그램이 고 부하에서 효율적이고 반응이 유지되도록합니다. 실제 사례를 결합하여 인덱싱, 쿼리 최적화, 데이터베이스 설계 및 캐싱과 같은 심층적 인 주요 기술을 설명합니다. 1. 데이터베이스 아키텍처 설계 및 최적화 된 데이터베이스 아키텍처는 MySQL 성능 최적화의 초석입니다. 몇 가지 핵심 원칙은 다음과 같습니다. 올바른 데이터 유형을 선택하고 요구 사항을 충족하는 가장 작은 데이터 유형을 선택하면 저장 공간을 절약 할 수있을뿐만 아니라 데이터 처리 속도를 향상시킬 수 있습니다.

See all articles