Replication Tips and Tricks in MySQL

Replication Tips and Tricks in MySQL

In March's "LAMP Post" column, we started to look at MySQL's replication subsystem. We covered how replication works, as well as putting it to use by configuring the master and slave(s). This month, in this inaugural "MySQL" column, let's spend some time looking at the lesser known aspects of MySQL replication, including filtering and log inspection.


In March’s “LAMP Post” column, we started to look at MySQL’s replication subsystem. We covered how replication works, as well as putting it to use by configuring the master and slave(s). This month, in this inaugural “MySQL” column, let’s spend some time looking at the lesser known aspects of MySQL replication, including filtering and log inspection.


Filtering on the Master


There are times when you’d rather not replicate all the data from a master to its slave(s). For instance, your master database server may contain test or pre-production databases and typically these databases, much like the /tmp directory on Linux, really don’t need to survive after a disaster. Rather than wasting the bandwidth and disk space to replicate them, you can tell MySQL to simply ignore them. You can accomplish this by adding one or more configuration directives to the my.cnf file on the master.


Let’s assume that you’re using the test database on your master, but don’t wish to log any changes to tables in test to the master’s binary log. Simple add a line like binlog-ignore -db=test to my.conf file. Of course, you’ll need to restart MySQL for the change to take effect. If you want to ignore multiple databases, either specify a list…



binlog-ignore-db=test,scratch



… or add one entry per database:



binlog-ignore-db=test

binlog-ignore-db=scratch



If, on the other hand, you’d rather provide a list of databases to replicate and let MySQL ignore the rest, use the binlog-do-db directive to specify them.



binlog-do-db=catalog

binlog-do-db=users

binlog-do-db=sessions



binlog-do-db tends to be the most practical if you have a small, fixed number of databases to replicate or when it’s likely that someone will be creating temporary databases on the master that need not be replicated.


Now, you may be wondering how MySQL decides what to do when filtering is involved. Typically, you’re not going to specify a database in every query you issue. You can do so by fully qualifying every table or column in dbname.tablename.colname format, but that’s tedious and not necessary.


Instead, most software connects to a specific database and uses that one database for the duration of the connection. In PHP, for example, you might issue a mysql_connect() call followed by a mysql_select_db() to set the default database for that connection. Or, if you’re using the mysql command-line client, you may specify a database name on the command-line or employ the USE command to switch databases after connecting, as in USE testdb;.


No matter how you do it, MySQL considers only the database you’ve selected as the default database when evaluating binary log filtering rules. While this works quite well 98 percent of the time, there may be times when you need to perform cross-database operations or when you’re lazy and change data in one database while actually using a different one as your default.


To make this more concrete, let’s assume you’ve connected to MySQL and are using the sessions database. If the last three binlog-do-db rules (above) are in effect and you issue a query like this…



DELETE FROM oldstuff.user_list



… MySQL will still write the query to the binary log. Why? Because you were connected to (or USEing) the sessions database, which is in the list of database you asked it to log changes to.


MySQL does not evaluate the query you’re executing when deciding whether to log it. Even though this query affected only a database that you asked it not to log, it doesn’t bother to notice.


The correct approach is to use the correct database when issuing queries that change data:



USE oldstuff

DELETE FROM user_list



Otherwise you’ll end up with a nasty surprise. Because the query was logged to the binary log, the slave’s I/O thread copies it to its relay log and the slave’s SQL thread attempts to execute it. However, odds are that the slave doesn’t have a copy of the oldstuff database (otherwise you’d probably have asked for it to be replicated), so the SQL thread will record an error in the MySQL error log and then stop executing queries from the relay log. You’ll then need to fix the problem.


The easiest solution is to ask the slave to skip ahead to the next query in the relay log and then continue executing:



SET SQL_SLAVE_SKIP_COUNTER = 1;

SLAVE START SQL_THREAD;



Then, of course, go find out what (or who) was too lazy to change databases when executing the DELETE in the first place.


Filtering on the Slave


So far, we’ve only considered filtering on the master’s end of replication. However, it’s also possible to apply filtering on the slave. This is important because you may need to have different policies for different slaves.


For example, your backup master may need to replicate everything that the master has, while your slaves that live 1,500 miles away need only a subset of the data. The good news is that you have quite a bit more flexibility on the slave’s side of things.


To start with, you can perform per-database filtering, just like on the master. The difference is that the directives begin with replicate rather than binlog. So, to allow the database users to replicate from a master, you could specify:



replicate-do-db=users



Or, to prevent replication of temporary, you could use:



replicate-ignore-db=temporary



But on the slave end you have even more granularity. Filtering (inclusive and exclusive) can be done down to the table level using these two directives…



replicate-do-table=dbname.tablename

replicate-do-ignore=dbname.tablename



… and to make things even more interesting, you can provide wildcard base “do” and “ignore” rules too.



replicate-wild-do-table=dbname.tablename

replicate-wild-ignore-table=dbname.tablename



In the wildcard directives, you may use the standard SQL wildcard characters (_ (“underscore”) for a single character and % for multiple characters) in both the database and table names.


Finally, you even have the option of rewriting the database name on the fly:



replicate-rewrite-db=oldname->newname



That tells the slave that any queries run in the oldname database on the master should be executed against newname on the slave.


One important aspect of slave-side filtering is that the slave has to see the queries before it can decide to either skip or execute them. That means slave filtering still uses up some of your network bandwidth. The slave’s I/O thread must copy all of the queries from the master’s binary log into the slave’s relay log. Only then can the slave’s SQL thread check each query against the “do” and “ignore” rules.


Log Inspection


Have you ever wondered what’s inside the binary log? In addition to the SQL for each query, the master records a few extra bits of metadata as well. You can use the mysqlbinlog tool to convert binary logs back into human- (and machine-) readable format.



$ mysqlbinlog binary-log.002



That command might produce output that looks like this (wrapped and reformatted for readability):



#040304 5:34:04 server id 103 log_pos

  32050 Intvar

SET INSERT_ID=277;



That first entry provides, as a comment, the date and time of the query, the id of the server it was first executed on, the log position, and the type of event. In this case, Intvar means that one of MySQL’s internal variables is being set — the INSERT_ID is used to tell a slave the auto-increment ID to be used in the next query it sees.



#040304 5:34:04 server id 103 log_pos

  32078 Query

thread_id=26993141 exec_time=0

  error_code=0

SET TIMESTAMP=1078407244;

insert into history values (NULL,

  1014193,20040303,0.5,0.5,0.5,0.5,0,1);



This second entry again provides some interesting metadata as a comment before the query.


In this case, since it’s a Query event, we also see the id of the thread that originally executed it, as well as the execution time (in seconds) and the error code.


Then we see a timestamp being set. The server records the time at which every query is executed. Finally, we see the actual query. The NULL is presumably going to be replaced by the insert id seen in the first entry.

Reset the MYSQL root password after error 1045 Cannot log in to the MySQL server

How to reset the MYSQL root password after error 1045 Cannot log in to the MySQL server

How to reset the MYSQL root password.
The MYSQL root is a different account with a different password than the Linux root. This tripped us up when we recently installed Mantis bug tracker and got a #1045 Cannot log in to the MySQL server error from PHPMYADMIN and the command line MYSQL login.
Here's how we reset the password on a Debian Linux system from an SSH command prompt.

Procedure

First check in /root/.my.cnf
below is permission
-rw-------.  1 root root       39 May 22 17:09 .my.cnf
cat /root/.my.cnf
[client]
password="p@ssw0rD&"
user=root
 
sudo /etc/init.d/mysql stop  

First stop MYSQL. Any part of your site that uses the database will return an error, so be ready to proceded quickly.
sudo mysqld_safe --skip-grant-tables --skip-networking &

Start MYSQL in safe mode with with passwords and network access disabled.
  • --skip-grant-tables option disables password protection for the database
  • --skip-networking disables network access to prevent attacks while passwords are disabled
  • & runs the process in the background
You might have to hit space to return to the command prompt.
sudo mysql -u root
Login as root, a password is not required.

MYSQL> use mysql;  ##note##optional
MYSQL> UPDATE user SET Password=PASSWORD('new_pass') WHERE User='root';
MYSQL> FLUSH PRIVILEGES;
MYSQL> exit;
Run these SQL statements at the MYSQL> prompt. Don't type MYSQL>...
  1. First set the new password for the root user. replace new_pass with your password
  2. Flush the privileges to reset everything
  3. Quit the MYSQL prompt
sudo /etc/init.d/mysql stop
Now stop MYSQL again.
sudo /etc/init.d/mysql start
Start MYSQL in normal mode.
sudo mysql -u root -p
To test the new password login as root with the password (-p) option enabled.
That's it, you're done!

Postfix part 6 courier authdaemond,pop/ pops ,imap/imapssl ,Squirrelmail

yum groupinstall  'Development Tools'
yum install expect
yum install gdbm*
yum install libtool-ltdl libtool-ltdl-devel -y

wget ftp://ftp.muug.mb.ca/mirror/redhat/redhat/linux/6.2/en/os/i386/RedHat/RPMS/gdbm-devel-1.8.0-3.i386.rpm

yum install gdbm-devel-1.8.0-3.i386.rpm
yum install gdb

                Download Courier AUTHLIB                   
wget http://cznic.dl.sourceforge.net/project/courier/authlib/0.66.1/courier-authlib-0.66.1.tar.bz2
tar xjvf courier-authlib-0.66.1.tar.bz2
cd /home/salman/courier-authlib-0.66.1
./configure                        #nonroot user
make install                     # root user
make install-configure      # root user

[root@server1 sbin]# pwd
/usr/local/sbin
[root@server1 sbin]# ls -al
total 152
drwxr-xr-x.  2 root root  4096 Jun 21 23:52 .
drwxr-xr-x. 12 root root  4096 Jun 21 23:52 ..
-rwxr-xr-x.  1 root root   433 Jun 21 23:52 authdaemond
-rwxr-xr-x.  1 root root 10933 Jun 21 23:52 authenumerate
-rwxr-xr-x.  1 root root 10806 Jun 21 23:52 authpasswd
-rwxr-xr-x.  1 root root 15304 Jun 21 23:52 authtest
-rwxr-xr-x.  1 root root 29157 Jun 21 23:52 courierlogger
-rwxr-xr-x.  1 root root  3293 Jun 21 23:52 makeuserdb
-rwxr-xr-x.  1 root root  1620 Jun 21 23:52 pw2userdb
-rwxr-xr-x.  1 root root  4792 Jun 21 23:52 userdb
-rwxr-xr-x.  1 root root 48011 Jun 21 23:52 userdbpw
-rwxr-xr-x.  1 root root  2095 Jun 21 23:52 userdb-test-cram-md5

The entire process installs the binaries and configuration files. Binary named “authdaemond” under “/usr/local/sbin” directory is executing as the authlib daemon. This consults the /usr/local/etc/authlib/authdaemonrc configuration file.

Starting the authlib daemon            
  [root@server1 ~]# /usr/local/sbin/authdaemond start
Starting authdaemond at startup     
# ln -s /usr/local/sbin/authdaemond /etc/init.d/
# ln -s /etc/init.d/authdaemond   /etc/rc.d/rc3.d/S24authdaemond

Installing courier imap (Installs the IMAP and POP3 service)
yum install openssl openssl-devel
\\\\\   As   Non Root user
                Download Courier IMAP                   
wget http://cznic.dl.sourceforge.net/project/courier/imap/4.15/courier-imap-4.15.tar.bz2

tar -xjvf courier-imap-4.15.tar.bz2
cd  courier-imap-4.15
./configure
make
# make install
# make install-configure


[root@server1 authlib]# pwd
/usr/local/etc/authlib
[root@server1 authlib]# ls
authdaemonrc  authdaemonrc.dist
The authdaemon consults authdaemonrc file ,we can change values like number of daemons and other performance related values
Starting authdaemond
# /usr/local/libexec/courier-authlib/authdaemond start


[root@server1 libexec]# pwd
/usr/lib/courier-imap/libexec
 [root@server1 libexec]# ./pop3d.rc start

allow necessary ports and disable selinux ,also check mynetworks,inet_interfaces= in main.cf

POP-SSL
Change the file /usr/lib/courier-imap/etc/pop3d.cnf  contents like email, CN etc for certificate
 Run the script:-
#./usr/lib/courier-imap/share/mkpop3dcert
cert file will be in same dir of script
#ls -l /usr/lib/courier-imap/share/
 total 24
drwxr-xr-x. 4 root root 4096 Jun 22 00:25 man
-rwxr-xr-x. 1 root root 1292 Jun 24 22:56 mkdhparams
-rwxr-xr-x. 1 root root 2319 Jun 24 22:56 mkimapdcert
-rwxr-xr-x. 1 root root 2179 Jun 24 22:56 mkpop3dcert
-rw-------. 1 root root 5463 Jun 24 23:00 pop3d.pem

To run pop-ssl we have to run the script /usr/lib/courier-imap/libexec/pop3d-ssl.rc
=>
# ./pop3d-ssl.rc start

TO enable pop3 and pop3ssl at runlevel/ startup we have to create sym-links to /etc/init.d/  and rc.d/
 for   pop
 [root@server1 ~]# ln -s /usr/lib/courier-imap/libexec/pop3d.rc /etc/init.d/
for pop-SSL
[root@server1 ~]# ln -s /usr/lib/courier-imap/libexec/pop3d-ssl.rc  /etc/init.d/
#ls -l /etc/init.d/
 ..
lrwxrwxrwx. 1 root root    38 Jun 24 23:18 pop3d.rc -> /usr/lib/courier-imap/libexec/pop3d.rc 
lrwxrwxrwx. 1 root root    42 Jun 24 23:20 pop3d-ssl.rc -> /usr/lib/courier-imap/libexec/pop3d-ssl.rc
..
...
above will only create shortcut now creating symlink to symlink @ runlevel directory thats /etc/rc.d/
[root@server1 ~]# ls /etc/rc.d/
init.d/     rc0.d/      rc2.d/      rc4.d/      rc6.d/      rc.sysinit 

rc          rc1.d/      rc3.d/      rc5.d/      rc.local 

Running in runlevel 3 :

ln -s /etc/init.d/pop3d-ssl.rc /etc/rc.d/rc3.d/S20pop3dssl
the name should be unique "S20pop3dssl"   , note=>S=start 

Starting pop and pop-ssl
[root@server1 rc3.d]# ./S21pop3d start
[root@server1 rc3.d]# ./S20pop3dssl start
 Check if port is listening by netstat -antpl

Setting up imap and imap ssl to run at runlevel 3 at start up
ln -s /usr/lib/courier-imap/libexec/imapd.rc /etc/init.d/
ln -s /etc/init.d/imapd.rc /etc/rc.d/rc3.d/S22imapd
ln -s /usr/lib/courier-imap/libexec/imapd-ssl.rc /etc/init.d/ln -s /etc/init.d/imapd-ssl.rc /etc/rc.d/rc3.d/S23imapssld



Install squirrel mail
#yum install httpd   mod_ssl
#yum install squirrelmail
To  deal with ERROR: Could not complete request. Query: CREATE "Sent" Reason Given: Invalid mailbox name. Follow below steps:-
      * If you use Courier and SquirrelMail Fedora RPM (1.4.4-2) - remove $default_folder_prefix override from /etc/squirrelmail/config_local.php
#vim /etc/squirrelmail/config_local.php
<?php
/**
 * Local config overrides.
 *
 * You can override the config.php settings here.
 * Don't do it unless you know what you're doing.
 ....
#comment below line if it is not
#$default_folder_prefix         = '';
?>
Configuring squirrel mail :-
cd /usr/share/squirrelmail/config
 [root@server1 config]# ./conf.pl
SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1.  Organization Preferences
2.  Server Settings
3.  Folder Defaults
4.  General Options
5.  Themes
6.  Address Books
7.  Message of the Day (MOTD)
8.  Plugins
9.  Database
10. Languages
D.  Set pre-defined settings for specific IMAP servers
C   Turn color off
S   Save data
Q   Quit

Command >> D
SquirrelMail Configuration : Read: config.php
---------------------------------------------------------
Please select your IMAP server:
    bincimap    = Binc IMAP server
    courier     = Courier IMAP server
    cyrus       = Cyrus IMAP server
    dovecot     = Dovecot Secure IMAP server
    exchange    = Microsoft Exchange IMAP server
    hmailserver = hMailServer
    macosx      = Mac OS X Mailserver
    mercury32   = Mercury/32
    uw          = University of Washington's IMAP server
    gmail       = IMAP access to Google mail (Gmail) accounts
    quit        = Do not change anything
Command >>courier    <press enter>

Configuring  SSL for squirrelmail
Generating private key :-
openssl genrsa -des3 -out privatekey22.pem 2048
Generate SSL certificate
openssl req -new -key privatekey22.pem -out self-ssl.csr

Remove passphrase for nginx (optional)

# openssl rsa -in privatekey22.pem -out privatekey.key    

# 
openssl x509 -req -days 365 -in self-ssl.csr -signkey privatekey.key -out selfsign.crt  


#vim /etc/httpd/conf.d/ssl.conf
 ##replace below value with --
SSLCertificateFile   /etc/httpd/ssl/selfsign.crt
SSLCertificateKeyFile /etc/httpd/ssl/privatekey.key


#service httpd start
#chkconfig httpd on


 




resync master-slave replication

root@rsus [~]# ls -al /root/
-rw-------   1 root root     39 Dec 18  2013 .my.cnf
 root@rs03us [~]# cat .my.cnf
[client]
password="#$6pqo<4"
user=root



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

This is the full step-by-step procedure to resync a master-slave replication from scratch:
At the master:
RESET MASTER; FLUSH TABLES WITH READ LOCK; SHOW MASTER STATUS;
And copy the values of the result of the last command somewhere.
Wihtout closing the connection to the client (because it would release the read lock) issue the command to get a dump of the master:
mysqldump -uroot -p --all-databases > /a/path/mysqldump.sql

NOTE: With INNODB typed dabatase and other complex column types like BLOB and DATE defined, recommend using the following switches: --opt --single-transaction --comments --hex-blob --dump-date --no-autocommit --all-databases

Now you can release the lock, even if the dump hasn't end. To do it perform the following command in the mysql client:
UNLOCK TABLES;
Now copy the dump file to the slave using scp or your preferred tool.
At the slave:
Open a connection to mysql and type:
STOP SLAVE;
Load master's data dump with this console command:
mysql -uroot -p < mysqldump.sql
Sync slave and master logs:
RESET SLAVE; CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=98;
Where the values of the above fields are the ones you copied before.
Finally type
START SLAVE;
And to check that everything is working again, if you type
SHOW SLAVE STATUS;
you should see:
Slave_IO_Running: Yes Slave_SQL_Running: Yes

= = = = = = Error : mysql out of resources = = = = = = = 
The mysql error:  Out of resources when opening file... (Errcode: 24)   indicates that the number of files that msyql is permitted to open has been exceeded. 
 Last_SQL_Error: Error 'Out of resources when opening file './thssedu_scl/' (Errcode: 24)' on query. Default database: 'thssedu_scl'. Query: 'ALTER TABLE thss_bsk_pdf_manager_cats CHANGE COLUMN id `id` int(11) NOT NULL AUTO_INCREMENT'

 
root@localhost [~]# mysql -e 'show variables;' | grep open
have_openssl    DISABLED
innodb_open_files    300
open_files_limit    1024    
table_open_cache    400


we have to increase that value:

vim /etc/my.cnf
[mysqld]
open_files_limit = 2024
 
 Then be sure to restart mysql with:   sudo /etc/init.d/mysql restart
A good rule of thumb is to take the current number of files and add 1000 to it. If this doesn't help, add some more.  This number affects the amount of memory that MySQL uses, so setting it to a very high number is not a good idea.

 

Rebuild your the default CentOS yum.repo.d folder

On a dev machine, somehow, I managed to erase my yum.repo.d contents. I wanted to rebuild the repo files back to their default. First you need to figure out what version you are using:
  • cat /etc/redhat-release
Then visit the correct release at : http://vault.centos.org/
  • navigate to the correct os/x86_64/CentOS/ directory (could be os/x86_64/CentOS/ i386/)
  • Download the following files to the server:
    • wget http://vault.centos.org/5.x/os/x86_64/CentOS/centos-release-notes-5.x-0.x86_64.rpm
    • wget http://vault.centos.org/5.x/os/x86_64/CentOS/centos-release-5-x.el5.centos.x86_64.rpm
  • Then install the two rpms:
    • rpm -Uivh *.rpm
Should be back to the original shipping repo files.

openssl update

#yum reinstall openssl
 = = == = == == == == == = =
To manually compile OpenSSL, do as follows:
$ cd /usr/src

$ wget https://www.openssl.org/source/openssl-1.0.1g.tar.gz -O openssl-1.0.1g.tar.gz

$ tar -zxf openssl-1.0.1g.tar.gz

$ cd openssl-1.0.1g

$ ./config

$ make

$ make test

$ make install

$ openssl version
 
If it shows the old version, do the steps below.
$ mv /usr/bin/openssl /root/ $ ln -s /usr/local/ssl/bin/openssl /usr/bin/openssl openssl version OpenSSL 1.0.1g 7 Apr 2014
 

Multiple MySQL Instance on linux



Create multiple mysql instance in CentOS 6.5 and Red Hat 6.5. Multiple instance means in single system we can create multiple MySQL server. These multiple mysql server will run in different ports.
Note:install mysql server
 
To create multiple MySQL instance,follow the given below steps
Login as a root in a system
Step (1): Create a new MySQL data directory.
mkdir -p /var/lib/mysql2

Step 2: Now give permission and ownership .Here we are taking ownership and permission reference from original /var/lib/mysql data directory.
Note: /var/lib/mysql is bydefault data directory path

chmod --reference /var/lib/mysql /var/lib/mysql2
chown --reference /var/lib/mysql /var/lib/mysql2
Step 3: Now create a new my2.cnf file and paste the below given contents. We will run the new mysql instance in port no. 3337.

Copy the my.cnf file and make it blank
cp -p /etc/my.cnf /etc/my2.cnf
Now edit with vi editor or your favorite editor.
vi /etc/my2.cnf

Edit in [mysqld] and [mysqld_safe] section as given below in my2.cnf file

[mysqld]
datadir=/var/lib/mysql2
socket=/var/lib/mysql/mysql2.sock
port=3337

[mysqld_safe]
log-error=/var/log/mysqld2.log
pid-file=/var/run/mysqld/mysqld2.pid

Step 4: Now install the database in the new mysql data directory
mysql_install_db --user=mysql --datadir=/var/lib/mysql2

Below given is the output from my server (as a Reference)
[root@localhost etc]# mysql_install_db --user=mysql --datadir=/var/lib/mysql2
Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h localhost.localdomain password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd /usr/mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

= = = = = = = = = = = = = = = = =
Step 5: Now the new instance is ready.Now in below section we will learn how to start,stop the mysql instance and how to connect with it.
Note: new mysql instance is running in port no. 3337 as per this tutorial
To start new mysql instance,use below given command
mysqld_safe --defaults-file=/etc/my2.cnf &
Now check the port no. 3337 is listening or not
netstat -tanp |grep 3337
To connect new mysql instance
Syntax:  mysql -u username -p -h 127.0.0.1 -P port-no.
As per our tutorial:
mysql -u root -p -h 127.0.0.1 -P 3337
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.1.71 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
It will ask password,hit enter because root password is blank
Now set root password (It is upto your choice, for security reason it is recommended).You can see mysql prompt.
mysql > use mysql;
mysql > update user set password=PASSWORD("Give-here-new-root-PASSWORD") where user='root';
mysql > flush privileges;
mysql > exit
Recheck if MySQL root password is applied or not

mysql -u root -p -h 127.0.0.1 -P 3337
To stop new mysql instance use below given command
mysqladmin -S /var/lib/mysql/mysql2.sock shutdown -p
Note: By using same method you can create multiple instance ,only you have to change the values like mysql2 to mysql3 or so on