Navigation

    • Login
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    1. Home
    2. Josh
    Josh

    Josh

    @Josh

    0
    Reputation
    4
    Posts
    1
    Profile views
    0
    Followers
    0
    Following
    Joined Last Online

    • Profile
    • More
      • Following
      • Followers
      • Topics
      • Posts
      • Best
      • Groups
    Josh Follow

    Best posts made by Josh

    This user hasn't posted anything yet.

    Latest posts made by Josh

    Operation MySQL Database in CentOS 7

    Operation MySQL Database in CentOS 7

    1. How to Manage MySQL Databases and Users from the Command Line

    Before you begin

    Before you start with this tutorial, we are assuming that you already have MySQL or MariaDB server installed on your system. All commands will be executed as a root user.
    To open the MySQL prompt, type the following command and enter the MySQL root user password when prompted:

    mysql -u root -p
    

    1)Create a new MySQL database

    To create a new MySQL database run the following command, just replace database_name with the name of the database that you want to create:

    CREATE DATABASE database_name;
    Query OK, 1 row affected (0.00 sec)
    

    If you try to create a database that already exists you will see the following error message:

    ERROR 1007 (HY000): Can't create database 'database_name'; database exists
    

    To avoid errors if the database with the same name as you are trying to create exists you can use the following command:

    CREATE DATABASE IF NOT EXISTS database_name;
    Query OK, 1 row affected, 1 warning (0.00 sec)
    

    In the output above, Query OK means that the query was successful, and 1 warning tells us that the database already exists and no new database was created.

    2)List all MySQL databases

    You can list all databases that exist on our MySQL or MariaDB server with the following command:

    SHOW DATABASES;
    

    The output will look something like this:

    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | database_name      |
    | mysql              |
    | performance_schema |
    | sys                |
    +--------------------+
    5 rows in set (0.00 sec)
    

    The information_schema, mysql, performance_schema, and sys databases are created at installation time and they are storing information about all other databases, system configuration, users, permission and other important data. These databases are necessary for the proper functionality of the MySQL installation.

    3)Delete a MySQL database

    Deleting a MySQL database is as simple as running a single command. This is a non-reversible action and should be executed with caution. Make sure that you are not removing a wrong database, as once you delete the database it cannot be recovered.
    To delete a MySQL or MariaDB, database run the following command:

    DROP DATABASE database_name;
    Query OK, 0 rows affected (0.00 sec)
    

    If you try to delete a database that doesn’t exist you will see the following error message:

    ERROR 1008 (HY000): Can't drop database 'database_name'; database doesn't exist
    

    To avoid this error you can use the following command:

    DROP DATABASE IF EXISTS database_name;
    

    4)Create a new MySQL user account

    A user account in MySQL consists of a user name and host name parts.
    To create a new MySQL user account run the following command, just replace ‘database_user’ with the name of the user that you want to create:

    CREATE USER 'database_user'@'localhost' IDENTIFIED BY 'user_password';
    

    In the command above we have set the hostname part to localhost which means that this user will be able to connect to the MySQL server only from the localhost ( i.e from the system where MySQL Server runs). If you want to grant access from another host(s) just change the localhost with the remote machine IP or use '%' wildcard for the host part, which means that the user account will be able to connect from any host.
    Same as when working with the databases to avoid an error when trying to create a user account which already exists you can use:

    CREATE USER IF NOT EXISTS 'database_user'@'localhost' IDENTIFIED BY 'user_password';
    Query OK, 0 rows affected, 1 warning (0.00 sec)
    

    4)Change a MySQL user account password

    The syntax for changing a MySQL or MariaDB user account password depends on the server version you are running on your system.
    You can find your server version by issuing the following command:

    mysql --version
    

    If you have MySQL 5.7.6 and newer or MariaDB 10.1.20 and newer, to change the password use the following command:

    ALTER USER 'database_user'@'localhost' IDENTIFIED BY 'new_password';
    

    If you have MySQL 5.7.5 and older or MariaDB 10.1.20 and older, then use:

    SET PASSWORD FOR 'database_user'@'localhost' = PASSWORD('new_password');
    

    In both cases, the output should look like this:

    Query OK, 0 rows affected (0.00 sec)
    

    5)List all MySQL user accounts

    You can list all MySQL or MariaDB user accounts by querying the mysql.users table:

    SELECT user, host FROM mysql.user;
    

    The output should look similar to below:

    +------------------+-----------+
    | user             | host      |
    +------------------+-----------+
    | database_user    | %         |
    | database_user    | localhost |
    | debian-sys-maint | localhost |
    | mysql.session    | localhost |
    | mysql.sys        | localhost |
    | root             | localhost |
    +------------------+-----------+
    6 rows in set (0.00 sec)
    

    6)Delete MySQL user account

    To delete a user account , use the following command:

    DROP USER 'database_user@'localhost';
    

    If you try to delete a user account which doesn’t exist an error will occur.

    ERROR 1396 (HY000): Operation DROP USER failed for 'database_user'@'localhost'
    

    Same as when working with the databases to avoid the error you can use:

    DROP USER IF EXISTS 'database_user'@'localhost';
    Query OK, 0 rows affected, 1 warning (0.00 sec)
    

    7)Grant permissions to a MySQL user account

    There are multiple types of privileges that can be granted to a user account. You can find a full list of privileges supported by MySQL here . In this guide we will go through several examples:
    To grand all privileges to a user account over a specific database, use the following command:

    GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
    

    To grand all privileges to a user account over all databases, use the following command:

    GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';
    

    To grand all privileges to a user account over a specific table from a database, use the following command:

    GRANT ALL PRIVILEGES ON database_name.table_name TO 'database_user'@'localhost';
    

    If you want to grant only specific privileges to a user account over a specific database type:

    GRANT SELECT, INSERT, DELETE ON database_name.* TO database_user@'localhost';
    

    8)Revoke permissions from a MySQL user account

    If you need to revoke one or more privileges or all privileges from a user account, the syntax is almost identical to granting it. For example, if you want to revoke all privileges from a user account over a specific database, use the following command:

    REVOKE ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
    

    9)Display MySQL user account privileges

    To find the privilege(s) granted to a specific MySQL user account type:

    SHOW GRANTS FOR 'database_user'@'localhost';
    +---------------------------------------------------------------------------+
    | Grants for database_user@localhost                                        |
    +---------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'database_user'@'localhost'                         |
    | GRANT ALL PRIVILEGES ON `database_name`.* TO 'database_user'@'localhost'  |
    +---------------------------------------------------------------------------+
    2 rows in set (0.00 sec)
    

    Conclusion

    This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to manage MySQL databases and users from the command line. You can also check the tutorial about how to reset a MySQL root password in case you have forgotten it.

    2. How to Reset the MySQL Root Password

    Too many password to remember? forgotten our MySQL root password? Don’t worry, it happens to all of us.
    In this article, we will show you how to reset the MySQL root password from the command line.

    1)Identify the Server Version

    Depending on the MySQL or MariaDB server version you are running on your system, you will need to use different commands to recover the root password.
    You can find your server version by issuing the following command:

    mysql --version
    

    If you have MySQL installed in your system the output will look something like this:

    mysql  Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using  EditLine wrapper
    

    Or output like this for MariaDB:

    mysql  Ver 15.1 Distrib 10.1.33-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
    

    Be sure to make a note of which version of MySQL or MariaDB you’re running.

    2)How to Reset MySQL or MariaDB Root Password

    Follow these steps to reset your MySQL/MariaDB root password:
    1. Stop the MySQL/MariaDB service
    To change the root password first, you need to stop the MySQL server. To do so type the following command:

    sudo systemctl stop mysql
    

    2. Start the MySQL/MariaDB server without loading the grant tables
    Start the database server without loading the grant tables:

    sudo mysqld_safe --skip-grant-tables &
    

    The ampersand & at the end of the command above will cause the program to run in the background, so you can continue to use the shell.
    When the

    --skip-grant-tables
    

    option is used, anyone can to connect to the database server without a password and with all privileges granted.

    3. Log in to the MySQL shell
    Now you can connect to the database server as the root user:
    mysql -u root
    4. Set a new root password

    • Run the following commands if you run MySQL 5.7.6 and later or MariaDB 10.1.20 and later:
    ALTER USER 'root'@'localhost' IDENTIFIED BY 'MY_NEW_PASSWORD';FLUSH PRIVILEGES;
    

    If ALTER USER statement doesn’t work for you, try to modify the user table directly:

    UPDATE mysql.user SET authentication_string = PASSWORD('MY_NEW_PASSWORD')
    WHERE User = 'root' AND Host = 'localhost';
    FLUSH PRIVILEGES;
    

    Run the following commands if you have MySQL 5.7.5 and earlier or MariaDB 10.1.20 and earlier:

    SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MY_NEW_PASSWORD');
    FLUSH PRIVILEGES;
    

    In both cases if all goes well, you should see the following output:

    Query OK, 0 rows affected (0.00 sec)
    

    5. Stop and Start the database server normally
    Now that the root password is set, stop the database server and start it normally:

    mysqladmin -u root -p shutdown
    

    You will be prompted to enter the new root password.
    Start the database server normally:
    For MySQL, type:

    sudo systemctl start mysql
    

    For MariaDB, type:

    sudo systemctl start mariadb
    

    6. Verify the password
    To verify that the new root password has been applied correctly, type:

    mysql -u root -p
    

    You will be prompted to enter the new root password. Enter it, and you should be logged in to your database server.

    Conclusion

    We’ve shown you how to reset your MySQL/MariaDB root password. Make sure your new root password is strong and secure and keep it in a safe place.
    The instructions in this guide should work with any modern Linux distribution such as Ubuntu 18.04, Debian 10 and CentOS 8.

    3. How to Create and Select MySQL Databases

    MySQL is the most popular open-source relational database management system.
    This tutorial explains how to create MySQL or MariaDB databases through the command line.

    Before you begin

    We are assuming that you already have MySQL or MariaDB server installed on your system.
    All commands are executed as an administrative user (the minimum privilege required to create a new database is CREATE) or with a root account.
    To access the MySQL shell type the following command and enter your MySQL root user password when prompted:

    mysql -u root -p
    

    If you haven’t set a password for your MySQL root user, you can omit the -p option.

    Create a MySQL Database

    Creating a new MySQL database is as simple as running a single command.
    To create a new MySQL or MariaDB database issue the following command, where database_name is the name of the database you want to create:

    CREATE DATABASE database_name;
    Query OK, 1 row affected (0.00 sec)
    

    If you try to create a database that already exists, you will see the following error message:

    ERROR 1007 (HY000): Can't create database 'database_name'; database exists
    

    To avoid errors if the database with the same name as you are trying to create exists, use the IF NOT EXISTS statement:

    CREATE DATABASE IF NOT EXISTS database_name;
    Query OK, 1 row affected, 1 warning (0.00 sec)
    

    In the output above, Query OK means that the query was successful, and 1 warning tells us that the database already exists, and no new database was created.

    On Linux, MySQL database and table names are case sensitive.

    View All MySQL Databases

    To view the database you’ve created, from within the MySQL shell, execute the following command:

    SHOW DATABASES;
    

    The command above will print a list of all databases on the server. The output should be similar to this:

    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | database_name      |
    | mysql              |
    | performance_schema |
    | test               |
    +--------------------+
    5 rows in set (0.00 sec)
    

    Select a MySQL Database

    When you create a database, the new database is not selected for use.
    To select a database before you begin a MySQL session, use the following statement:

    USE database_name;
    Database changed
    

    Once you select a database, all the subsequent operations, such as creating tables, are performed on the selected database.
    Each time you want to work on a database, you must select it with the USE statement.
    You can also select the database when connecting to the MySQL server by appending the name of the database at the end of the command:

    mysql -u root -p database_name
    

    Create a MySQL Database with mysqladmin

    You can also use the mysqladmin utility to create a new MySQL database from the Linux terminal.
    For example, to create a database named database_name, you would use the following command:

    mysqladmin -u root -p create database_name
    

    Conclusion

    We have shown you how to create and select MySQL databases using the MySQL shell and mysqladmin command.

    4. How to Create MySQL Users Accounts and Grant Privileges

    MySQL is the most popular open-source relational database management system. MySQL server allows us to create numerous user accounts and grant appropriate privileges so that the users can access and manage databases.
    This tutorial describes how to create MySQL user accounts and grant privileges.

    Before you Begin

    We are assuming that you already have MySQL or MariaDB server installed on your system.
    All commands are executed inside the MySQL shell as root or administrative user. The minimum privileges required to create user accounts and define their privileges is CREATE USER and GRANT.
    To access the MySQL shell type the following command and enter your MySQL root user password when prompted:

    mysql -u root -p
    

    If you have MySQL version 5.7 or later that uses the auth_socket plugin login as root by typing:

    sudo mysql
    

    Create a new MySQL User Account

    A user account in MySQL consists of two parts: user name and host name.
    To create a new MySQL user account, run the following command:

    CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';
    

    Replace newuser with the new user name, and user_password with the user password.
    In the example above, the hostname part is set to localhost, which means that the user will be able to connect to the MySQL server only from the localhost (i.e. from the system where MySQL Server runs).
    To grant access from another host, change the hostname part with the remote machine IP. For example, to grant access from a machine with IP 10.8.0.5 you would run:

    CREATE USER 'newuser'@'10.8.0.5' IDENTIFIED BY 'user_password';
    

    To create a user that can connect from any host, use the '%' wildcard as a host part:

    CREATE USER 'newuser'@'%' IDENTIFIED BY 'user_password';
    

    Grant Privileges to a MySQL User Account

    There are multiple types of privileges that can be granted to a user account. You can find a full list of privileges supported by MySQL here .
    The most commonly used privileges are:

    • ALL PRIVILEGES – Grants all privileges to a user account.
    • CREATE – The user account is allowed to create databases and tables.
    • DROP - The user account is allowed to drop databases and tables.
    • DELETE - The user account is allowed to delete rows from a specific table.
    • INSERT - The user account is allowed to insert rows into a specific table.
    • SELECT – The user account is allowed to read a database.
    • UPDATE - The user account is allowed to update table rows.
      To grant specific privileges to a user account, use the following syntax:
    GRANT permission1, permission2 ON database_name.table_name TO 'database_user'@'localhost';
    

    Here are some examples:
    Grand all privileges to a user account over a specific database:

    GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
    

    Grand all privileges to a user account on all databases:

    GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';
    

    Grand all privileges to a user account over a specific table from a database:

    GRANT ALL PRIVILEGES ON database_name.table_name TO 'database_user'@'localhost';
    

    Grant multiple privileges to a user account over a specific database:

    GRANT SELECT, INSERT, DELETE ON database_name.* TO database_user@'localhost';
    

    Display MySQL User Account Privileges

    To find the privilege(s) granted to a specific MySQL user account, use the SHOW GRANTS statement:

    SHOW GRANTS FOR 'database_user'@'localhost';
    

    The output will look something like below:

    +---------------------------------------------------------------------------+
    | Grants for database_user@localhost                                       |
    +---------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'database_user'@'localhost'                        |
    | GRANT ALL PRIVILEGES ON `database_name`.* TO 'database_user'@'localhost' |
    +---------------------------------------------------------------------------+
    2 rows in set (0.00 sec)
    

    Revoke Privileges from a MySQL User Account

    The syntax to revoke one or more privileges from a user account is almost identical as when granting privileges.
    To revoke all privileges from a user account over a specific database, run the following command:

    REVOKE ALL PRIVILEGES ON database_name.* FROM 'database_user'@'localhost';
    

    Remove an Existing MySQL User Account
    To delete a MySQL user account use the DROP USER statement:

    DROP USER 'user'@'localhost'
    

    The command above will remove the user account and its privileges.

    Conclusion

    This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to create new MySQL user accounts and grant privileges.
    If you have any questions or feedback, feel free to leave a comment.

    5. How to Show/List Users in MySQL

    Have you ever needed to get a list of all users in your MySQL server? There are commands to show databases and tables, but there is no MySQL show users command.
    This tutorial explains how to list all user accounts in a MySQL database server through the command line. We’ll also show you how the find out which users have access to a given database.

    Before You Begin

    We are assuming that you already have MySQL or MariaDB server installed on your system.
    All commands are executed inside the MySQL shell as a root user. To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
    mysql -u root -p
    If you haven’t set a password for your MySQL root user, you can omit the -p option.

    Show All MySQL Users

    MySQL stores information about the users in a table named user in the mysql database.
    To get a list of all MySQL user accounts, use the SELECT statement to retrieve all rows from the mysql.users table:

    SELECT User, Host FROM mysql.user;
    

    The output should look similar to below:

    +------------------+-----------+
    | user             | host      |
    +------------------+-----------+
    | root             | localhost |
    | luke             | %         |
    | yoda             | %         |
    | jabba            | 10.10.0.6 |
    | jabba            | 10.10.0.9 |
    | chewbacca        | localhost |
    | leia             | localhost |
    | han              | localhost |
    +------------------+-----------+
    8 rows in set (0.00 sec)
    

    The command above shows only two columns from the mysql.user table (User and Host), This table contains more than 40 columns such as Password, Select_priv, Update_priv, etc.
    A user account in MySQL consists of two parts: a user name and hostname.
    Use the desc mysql.user; statement to display information about the table’s columns. Once you know the column name, you can run a query against a selected data.
    For example, to get a list of all MySQL users accounts including information about the password and whether it is active or expired, you would use the following query:

    SELECT User, Host, Password, password_expired FROM mysql.user;
    +----------------+-----------+-------------------------------------------+------------------+
    | User           | Host      | Password                                  | password_expired |
    +----------------+-----------+-------------------------------------------+------------------+
    | root           | localhost |                                           | N                |
    | luke           | %         | *ADC3B5B27617732CD6320A2DA976258E149A7EC8 | N                |
    | yoda           | %         | *9550E004046348198A143A115550E1262209FB6F | N                |
    | jabba          | 10.10.0.6 | *F91C86B486B945C083B61A05FF6E197560D187EC | Y                |
    | jabba          | 10.10.0.9 |                                           | Y                |
    | chewbacca      | localhost | *17F2B1E48029294841AD66772BEBB7E6E6A005AF | N                |
    | leia           | localhost | *74409C8DB55AC1A6829D801915981C46EDBFC64A | N                |
    | han            | localhost | *7B3022FCAEC3534CE67C68322D8AF0C240D95745 | N                |
    +----------------+-----------+-------------------------------------------+------------------+
    8 rows in set (0.00 sec)
    

    Show Users that Have Access to a Particular Database

    The information about the database-level privileges is stored in the mysql.db table.
    You can query the table to find out which users have access to a given database and the level of the privileges.
    For example, to get a list of all users that have some level access to the database named db_name you would use the following query:

    SELECT * FROM mysql.db WHERE Db = 'db_name'\G;
    *************************** 1. row ***************************
                     Host: localhost
                       Db: db_name
                     User: db_user
              Select_priv: Y
              Insert_priv: Y
              Update_priv: Y
              Delete_priv: Y
              Create_priv: Y
                Drop_priv: Y
               Grant_priv: N
          References_priv: Y
               Index_priv: Y
               Alter_priv: Y
    Create_tmp_table_priv: Y
         Lock_tables_priv: Y
         Create_view_priv: Y
           Show_view_priv: Y
      Create_routine_priv: Y
       Alter_routine_priv: Y
             Execute_priv: Y
               Event_priv: Y
             Trigger_priv: Y
    1 row in set (0.00 sec)
    

    To fetch information only about the user accounts that have access to a given database, without displaying the privileges use:

    SELECT db, host, user FROM mysql.db WHERE db = 'db_name'
    +---------+-----------+---------+
    | db      | host      | user    |
    +---------+-----------+---------+
    | db_name | localhost | db_user |
    +---------+-----------+---------+
    

    The following query will show you information about all databases and associated users:

    SELECT db, host, user FROM mysql.db;
    +------------------+-----------+-----------+
    | db               | host      | user      |
    +------------------+-----------+-----------+
    | db_name          | localhost | db_user   |
    | ghost_production | localhost | chewbacca |
    | blog_db          | localhost | leia      |
    | linuxize         | localhost | han       |
    +------------------+-----------+-----------+
    

    Conclusion

    In this tutorial, we have shown how to get a list of all MySQL users and find out which users have access to a particular database.

    6. How to Back Up and Restore MySQL Databases with Mysqldump

    This tutorial explains how to backup and restore MySQL or MariaDB databases from the command line using the mysqldump utility.
    The backup files created by the mysqldump utility are basically a set of SQL statements that can be used to recreate the original database. The mysqldump command can also generate files in CSV and XML format.
    You can also use the mysqldump utility to transfer your MySQL database to another MySQL server.
    If you don’t backup your databases, a software bug or a hard-drive failure could be disastrous. To help save you lots of time and frustration, it is strongly recommended that you take the precaution of regularly backing up your MySQL databases.

    Mysqldump Command Syntax

    Before going into how to use the mysqldump command, let’s start by reviewing the basic syntax.
    The mysqldump utility expressions take the following form:

    mysqldump [options] > file.sql
    
    • options - The mysqldump options
    • file.sql - The dump (backup) file

    To use the mysqldump command the MySQL server must be accessible and running.

    Backup a Single MySQL Database

    The most common use case of the mysqldump tool is to backup a single database.
    For example, to create a backup of the database named database_name using the user root and save it to a file named database_name.sql you would run the following command:

    mysqldump -u root -p database_name > database_name.sql
    

    You will be prompted to enter the root password. After successful authentication, the dump process will start. Depending on the database size, the process can take some time.
    If you are logged in as the same user that you are using to perform the export and that the user does not require a password, you can omit the -u and -p options:

    mysqldump database_name > database_name.sql
    

    Backup Multiple MySQL Databases

    To backup multiple MySQL databases with one command you need to use the --database option followed by the list of databases you want to backup. Each database name must be separated by space.

    mysqldump -u root -p --databases database_name_a database_name_b > databases_a_b.sql
    

    The command above will create a dump file containing both databases.

    Backup All MySQL Databases

    Use the --all-databases option to back up all the MySQL databases:

    mysqldump -u root -p --all-databases > all_databases.sql
    

    Same as with the previous example the command above will create a single dump file containing all the databases.

    Backup all MySQL databases to separate files

    The mysqldump utility doesn’t provide an option to backup all databases to separate files but we easily achieve that with a simple bash FOR loop :

    for DB in $(mysql -e 'show databases' -s --skip-column-names); do
        mysqldump $DB > "$DB.sql";
    

    done
    The command above will create a separate dump file for each database using the database name as the filename.

    Create a Compressed MySQL Database Backup

    If the database size is very large it is a good idea to compress the output. To do that simply pipe the output to the gzip utility, and redirect it to a file as shown below:

    mysqldump database_name | gzip > database_name.sql.gz
    

    Create a Backup with Timestamp

    If you want to keep more than one backup in the same location, then you can add the current date to the backup filename:

    mysqldump  database_name > database_name-$(date +%Y%m%d).sql
    

    The command above will create a file with the following format database_name-20180617.sql

    Restoring a MySQL dump

    You can restore a MySQL dump using the mysql tool. The command general syntax is as follows:

    mysql  database_name < file.sql
    

    In most cases you’ll need to create a database to import into. If the database already exists, first you need to delete it.
    In the following example the first command will create a database named database_name and then it will import the dump database_name.sql into it:

    mysql -u root -p -e "create database database_name";mysql -u root -p database_name < database_name.sql
    

    Restore a Single MySQL Database from a Full MySQL Dump

    If you backed up all your databases using the -all-databases option and you want to restore a single database from a backup file which contains multiple databases use the --one-database option as shown below:

    mysql --one-database database_name < all_databases.sql
    

    Export and Import a MySQL Database in One Command

    Instead of creating a dump file from one database and then import the backup into another MySQL database you can use the following one-liner:

    mysqldump -u root -p database_name | mysql -h remote_host -u root -p remote_database_name
    

    The command above will pipe the output to a mysql client on the remote host and it will import it into a database named remote_database_name. Before running the command, make sure the database already exists on the remote server.

    Automate Backups with Cron

    Automating the process of backing up the databases is as simple as creating a cron job what will run the mysqldump command at specified time.
    To set up automated backups of a MySQL database using cronjob, follow the steps below:
    Create a file named .my.cnf in your user home directory:

    sudo nano ~/.my.cnf
    

    Copy and paste the following text into the .my.cnf file.

    [client]
    user = dbuser
    password = dbpasswd
    
    • Do not forget to replace dbuser and dbpasswdwith the database user and user’s password.
    • Restrict permissions of the credentials file so that only your user has access to it:
    chmod 600 ~/.my.cnf
    

    Create a directory to store the backups:

    mkdir ~/db_backups
    

    Open your user crontab file:

    crontab -e
    

    Add the following cron job that will create a backup of a database name mydb every day at 3am:

    0 3 * * * /usr/bin/mysqldump -u dbuser mydb > /home/username/db_backups/mydb-$(date +\%Y\%m\%d).sql
    
    1. Do not forget to replace username with your actual user name. We’re also escaping the percent-signs (%), because they have special meaning in crontab.
      You can also create another cronjob to delete any backups older than 30 days:
    find /path/to/backups -type f -name "*.sql" -mtime +30 -delete
    

    Conclusion

    This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to create and restore MySQL databases from the command line using the mysqldump utility.

    posted in Tutorials & How To •
    How to Install MySQL on CentOS 7

    Install MySQL on CentOS 7

    With the release of CentOS 7 MySQL, the world’s most popular open-source relational database management system is no longer available in the CentOS’s repositories and MariaDB has become the default database system. MariaDB is a backward compatible, binary drop-in replacement of MySQL.
    In this tutorial, we will show you how to install MySQL on a CentOS 7 machine.

    Prerequisites

    • Deploy a Cybree Instance with CentOS 7 image.
    • Connect to your instance via Cybree VNC terminal, or use other terminal (such as Putty SSH) to connect your instance.
    • Login to account with sudo or root privileges. The default Centos administrator login name is "root". It is best practice to run administrative commands as sudo user instead of root, if you don’t have a sudo user on your system you can create one by following these instructions .
    • As we mentioned in the introduction MySQL is not available in the default CentOS 7 repositories so we will be installing the packages from the MySQL Yum Repository . In the following sections, we will show you how to install MySQL 8.0 and MySQL 5.7.
    • You should install only one MySQL version on your CentOS 7 server. If you are not sure which version to install consult the documentation of the applications you’re going to deploy on your server.

    Install MySQL 8.0 on CentOS 7

    At the time of writing this article, the latest version of MySQL is version 8.0. To install it on your CentOS 7 server follow the steps below:
    Enable the MySQL 8.0 repository with the following command:

    sudo yum localinstall https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
    

    Install MySQL 8.0 package with yum:

    sudo yum install mysql-community-server
    

    During the installation yum may prompt you to import the MySQL GPG key. Type y and hit Enter.

    Starting MySQL

    Once the installation is completed, start the MySQL service and enable it to automatically start on boot with:

    sudo systemctl enable mysqld
    sudo systemctl start mysqld
    

    We can check the MySQL service status by typing:

    sudo systemctl status mysqld
    

    Output

    mysqld.service - MySQL Server
       Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
       Active: active (running) since Wed 2021-05-1 11:02:43 UTC; 14min ago
         Docs: man:mysqld(8)
               http://dev.mysql.com/doc/refman/en/using-systemd.html
      Process: 4293 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
     Main PID: 4310 (mysqld)
       Status: "SERVER_OPERATING"
       CGroup: /system.slice/mysqld.service
               └─4310 /usr/sbin/mysqld
    

    Securing MySQL

    When the MySQL server is started for the first time, a temporary password is generated for the MySQL root user. You can find the password by running the following command:

    sudo grep 'temporary password' /var/log/mysqld.log
    

    The output should look something like this:

    2020-05-1T10:59:51.251159Z 5 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: x#0)B&?rpkra
    

    Make note of the password, because the next command will ask you to enter the temporary root password.
    Run the mysql_secure_installation command to improve the security of our MySQL installation:

    sudo mysql_secure_installation
    

    Output

    Securing the MySQL server deployment.
    
    Enter password for user root:
    

    After entering the temporary password you will be asked to set a new password for user root. The password needs to be at least 8-characters long and to contain at least one uppercase letter, one lowercase letter, one number, and one special character.
    Output

    The existing password for the user account root has expired. Please set a new password.
    
    New password:
    
    Re-enter new password:
    

    The script will also ask you to remove the anonymous user, restrict root user access to the local machine and remove the test database. You should answer “Y” (yes) to all questions.

    Connecting to MySQL from the command line

    To interact with MySQL through the terminal we will use the MySQL client which is installed as a dependency of the MySQL server package.
    To log in to the MySQL server as the root user type:

    mysql -u root -p
    

    You will be prompted to enter the root password you have previously set when the mysql_secure_installation script was run.
    Once you enter the password you will be presented with the mysql shell as shown below:
    Output

    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 11
    Server version: 8.0.11 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2018, 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.
    

    Create a Database

    Once you are connected to the MySQL shell, you can create a new database by typing the following command:

    CREATE DATABASE new_database;
    Query OK, 1 row affected (0.00 sec)
    

    Create Tables

    Now that we created a database we can create a table to store some data.
    Before running the SQL statements for creating a table we need to connect to the database:

    use new_database;
    

    In this example we will create a simple table named contacts with three fields, id, name and email:

    CREATE TABLE contacts (
      id INT PRIMARY KEY,
      name VARCHAR(30),
      email VARCHAR(30)
    );
    
    Query OK, 1 row affected (0.00 sec)
    

    Conclusion

    In this tutorial, we’ve shown you how to install and secure a MySQL server on a CentOS 7 server. We have also shown you how to connect to the MySQL shell and how to create a new database and table.

    posted in Tutorials & How To •
    Operation of Nginx on CentOS 7

    Operation of Nginx on CentOS 7

    1. Setting up Nginx Reverse Proxy

    A reverse proxy is a service that takes a client request, sends the request to one or more proxied servers, fetches the response, and delivers the server’s response to the client.
    Because of its performance and scalability, NGINX is often used as a reverse proxy for HTTP and non-HTTP servers. A typical reverse proxy configuration is to put Nginx in front of Node.js , Python , or Java applications.
    Using Nginx as a reverse proxy gives you several additional benefits:

    • Load Balancing - Nginx can perform load balancing to distribute clients' requests across proxied servers, which improve the performance, scalability, and reliability.
    • Caching - With Nginx as a reverse proxy, you can cache the pre-rendered versions of pages to speed up page load times. It works by caching the content received from the proxied servers' responses and using it to respond to clients without having to contact the proxied server for the same content every time.
    • SSL Termination - Nginx can act as an SSL endpoint for connections with the clients. It will handle and decrypt incoming SSL connections and encrypt the proxied server’s responses.
    • Compression - If the proxied server does not send compressed responses, you can configure Nginx to compress the responses before sending them to the clients.
    • Mitigating DDoS Attacks - You can limit the incoming requests and number of connections per single IP address to a value typical for regular users. Nginx also allows you to block or restrict access based on the client location, and the value of the request headers such as “User-Agent” and “Referer”.
      This article outlines the steps required for configuring Nginx as a reverse proxy.

    Prerequisites

    We are assuming that you have Nginx installed on your Ubuntu , CentOS , or Debian server.

    1)Using Nginx as a Reverse Proxy

    To configure Nginx as a reverse proxy to an HTTP server, open the domain’s server block configuration file and specify a location and a proxied server inside of it:

    server {
        listen 80;
        server_name www.example.com example.com;
    
        location /app {
           proxy_pass http://127.0.0.1:8080;
        }
    }
    

    The proxied server URL is set using the proxy_pass directive and can use HTTP or HTTPS as protocol, domain name or IP address, and an optional port and URI as an address.
    The configuration above tells Nginx to pass all requests to the /app location to the proxied server at http://127.0.0.1:8080.
    On Ubuntu and Debian based distributions, server block files are stored in the /etc/nginx/sites-available directory, while on CentOS in /etc/nginx/conf.d directory.
    To better illustrate how location and proxy_pass directives work, let’s take the following example:

    server {
        listen 80;
        server_name www.example.com example.com;
    
        location /blog {
           proxy_pass http://node1.com:8000/wordpress/;
        }
    }
    

    If a visitor access http://example.com/blog/my-post, Nginx will proxy this request to http://node1.com:8000/wordpress/my-post.
    When the address of the proxied server contains a URI, (/wordpress/), the request URI that is passed to the proxied server is replaced by a URI specified in the directive. If the address of the proxied server is specified without a URI, the full request URI is passed to the proxied server.

    2)Passing Request Headers

    When Nginx proxies a request, it automatically defines two header fields in a proxied requests from the client, Host and Connection, and removes empty headers. Host is set to the $proxy_host variable, and Connection is set to close.
    To adjust or set headers for proxied connections, use the proxy_set_header directive, followed by the header value. You can find a list of all available Request Headers and their allowed values here . If you want to prevent a header from being passed to the proxied server, set it to an empty string "".
    In the following example, we are changing the value of the Host header field to $host and removing the Accept-Encoding header field by setting its value to an empty string.

    location / {
        proxy_set_header Host $host;
        proxy_set_header Accept-Encoding "";
        proxy_pass http://localhost:3000;
    }
    

    Whenever you modify the configuration file, you have to restart the Nginx service for the changes to take effect.

    3)Configuring Nginx as a Reverse Proxy to a non-HTTP proxied server

    To configure Nginx as a reverse proxy to a non-HTTP proxied server, you can use the following directives:

    • fastcgi_pass - reverse proxy to a FastCGI server.
    • uwsgi_pass - reverse proxy to a uwsgi server.
    • scgi_pass - reverse proxy to an SCGI server.
    • memcached_pass - reverse proxy to a Memcached server.
      One of the most common examples is to use Nginx as a reverse proxy to PHP-FPM:
    server {
    
        # ... other directives
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
    }
    

    4)Common Nginx Reverse Proxy Options

    Serving content over HTTPS has become a standard nowadays. In this section, we will give you an example of HTTPS Nginx reverse proxy configuration including the recommended Nginx proxy parameters and headers.

    location/ {
      proxy_pass http://127.0.0.1:3000;
      proxy_http_version  1.1;
      proxy_cache_bypass  $http_upgrade;
    
    proxy_set_header Upgrade           $http_upgrade;
    proxy_set_header Connection        "upgrade";
    proxy_set_header Host              $host;
    proxy_set_header X-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host  $host;
    proxy_set_header X-Forwarded-Port  $server_port;
    

    }

    • proxy_http_version 1.1 - Defines the HTTP protocol version for proxying, by default it it set to 1.0. For Websockets and keepalive connections you need to use the version 1.1.
    • proxy_cache_bypass $http_upgrade - Sets conditions under which the response will not be taken from a cache.
    • Upgrade $http_upgrade and Connection "upgrade" - These header fields are required if your application is using Websockets.
    • Host $host - The $host variable in the following order of precedence contains: hostname from the request line, or hostname from the Host request header field, or the server name matching a request.
    • X-Real-IP $remote_addr - Forwards the real visitor remote IP address to the proxied server.
    • X-Forwarded-For $proxy_add_x_forwarded_for - A list containing the IP addresses of every server the client has been proxied through.
    • X-Forwarded-Proto $scheme - When used inside an HTTPS server block, each HTTP response from the proxied server is rewritten to HTTPS.
    • X-Forwarded-Host $host - Defines the original host requested by the client.
    • X-Forwarded-Port $server_port - Defines the original port requested by the client.
      If you don’t have an existing SSL/TLS certificate, use certbot to obtain a free Let’s Encrypt SSL certificate on your Ubuntu 18.04, CentOS 7, or Debian server.

    Conclusion

    You have learned how to use Nginx as a Reverse Proxy. We have also shown you how to pass additional parameters to the server and to modify and set different header fields in proxied requests

    2. Secure Nginx with Let's Encrypt on CentOS 7

    Let’s Encrypt is a free and open certificate authority developed by the Internet Security Research Group (ISRG). Certificates issued by Let’s Encrypt are trusted by almost all browsers today.
    In this tutorial, we’ll provide a step by step instructions about how to secure your Nginx with Let’s Encrypt using the certbot tool on CentOS 7.

    Prerequisites

    Make sure that you have met the following prerequisites before continuing with this tutorial:

    • You have a domain name pointing to your public server IP. In this tutorial we will use example.com.
    • You have enabled the EPEL repository and installed Nginx by following How To Install Nginx on CentOS 7 .

    1)Install Certbot

    Certbot is an easy to use tool that can automate the tasks for obtaining and renewing Let’s Encrypt SSL certificates and configuring web servers.
    To install the certbot package form the EPEL repository run:

    sudo yum install certbot
    

    2)Generate Strong Dh (Diffie-Hellman) Group

    Diffie–Hellman key exchange (DH) is a method of securely exchanging cryptographic keys over an unsecured communication channel.
    Generate a new set of 2048 bit DH parameters by typing the following command:

    sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
    

    Obtaining a Let’s Encrypt SSL certificate
    To obtain an SSL certificate for our domain we’re going to use the Webroot plugin that works by creating a temporary file for validating the requested domain in the ${webroot-path}/.well-known/acme-challenge directory. The Let’s Encrypt server makes HTTP requests to the temporary file to validate that the requested domain resolves to the server where certbot runs.
    To make it more simple we’re going to map all HTTP requests for .well-known/acme-challenge to a single directory, /var/lib/letsencrypt.
    The following commands will create the directory and make it writable for the Nginx server.

    sudo mkdir -p /var/lib/letsencrypt/.well-knownsudo chgrp nginx /var/lib/letsencryptsudo chmod g+s /var/lib/letsencrypt
    

    To avoid duplicating code create the following two snippets which we’re going to include in all our Nginx server block files:

    sudo mkdir /etc/nginx/snippets
    

    /etc/nginx/snippets/letsencrypt.conf

    location ^~ /.well-known/acme-challenge/ {
      allow all;
      root /var/lib/letsencrypt/;
      default_type "text/plain";
      try_files $uri =404;
    }
    

    /etc/nginx/snippets/ssl.conf

    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
    ssl_prefer_server_ciphers on;
    
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 30s;
    
    add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload";
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    

    The snippet above includes the chippers recommended by Mozilla , enables OCSP Stapling, HTTP Strict Transport Security (HSTS) and enforces few securityfocused HTTP headers.
    Once the snippets are created, open the domain server block and include the letsencrypt.conf snippet as shown below:
    /etc/nginx/conf.d/example.com.conf

    server {
      listen 80;
      server_name example.com www.example.com;
    
      include snippets/letsencrypt.conf;
    }
    

    Reload the Nginx configuration for changes to take effect:

    sudo systemctl reload nginx
    

    You can now run Certbot with the webroot plugin and obtain the SSL certificate files for your domain by issuing:

    sudo certbot certonly --agree-tos --email admin@example.com --webroot -w /var/lib/letsencrypt/ -d example.com -d www.example.com
    

    If the SSL certificate is successfully obtained, certbot will print the following message:

    OTES:
     - Congratulations! Your certificate and chain have been saved at:
       /etc/letsencrypt/live/example.com/fullchain.pem
       Your key file has been saved at:
       /etc/letsencrypt/live/example.com/privkey.pem
       Your cert will expire on 2018-06-11. To obtain a new or tweaked
       version of this certificate in the future, simply run certbot
       again. To non-interactively renew *all* of your certificates, run
       "certbot renew"
     - If you like Certbot, please consider supporting our work by:
    
       Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
       Donating to EFF:                    https://eff.org/donate-le
    

    Now that you have the certificate files, you can edit your domain ```
    server block as follows:
    /etc/nginx/conf.d/example.com.conf
    server {
    listen 80;
    server_name www.example.com example.com;

    include snippets/letsencrypt.conf;
    return 301 https://$host$request_uri;
    

    }

    server {
    listen 443 ssl http2;
    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
        include snippets/ssl.conf;
        include snippets/letsencrypt.conf;
    
        return 301 https://example.com$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name example.com;
    
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
        include snippets/ssl.conf;
        include snippets/letsencrypt.conf;
    # . . . other code
    }
    

    ``With the configuration above we are forcing HTTPS and redirecting the www to non www version.
    Finally, reload the Nginx service for changes to take effect:

    sudo systemctl reload nginx
    

    3)Auto-renewing Let’s Encrypt SSL certificate

    Let’s Encrypt’s certificates are valid for 90 days. To automatically renew the certificates before they expire, we will create a cronjob which will run twice a day and will automatically renew any certificate 30 days before its expiration.

    Run the crontab command to create a new cronjob:

    sudo crontab -e
    

    Paste the following lines:

    0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --renew-hook "systemctl reload nginx"
    

    Save and close the file.
    To test the renewal process, you can use the certbot command followed by the --dry-run switch:

    sudo certbot renew --dry-run
    

    If there are no errors, it means that the test renewal process was successful.

    Conclusion

    In this tutorial, you used the Let’s Encrypt client, certbot to download SSL certificates for your domain. You have also created Nginx snippets to avoid duplicating code and configured Nginx to use the certificates. At the end of the tutorial you have set up a cronjob for automatic certificate renewal.

    3.How to Set Up Nginx Server Blocks on CentOS 7

    Nginx Server Blocks allows you to run more than one website on a single machine. This is useful because for each site you can specify the site document root (the directory which contains the website files), create a separate security policy, use different SSL certificates, and much more.
    In this tutorial, we’ll explain how to set up Nginx server blocks on CentOS 7.

    Prerequisites

    Ensure that you have met the following prerequisites before continuing with this tutorial:

    • Domain name pointing to your public server IP. We will use example.com.
    • Nginx installed on your CentOS system.
    • Logged in as root or user with sudo privileges.
      In some documentation, you’ll see Server Blocks being referred to as a Virtual host. A virtual host is an Apache term.

    1)Create the Directory Structure

    The document root is the directory where the website files for a domain name are stored and served in response to requests. We can set the document root to any location you want.
    We will use the following directory structure:

    /var/www/
    ├── example.com
    │   └── public_html
    ├── example2.com
    │   └── public_html
    ├── example3.com
    │   └── public_html
    

    Basically we are creating a separate directory for each domain we want to host on our server inside the /var/www directory. Within this directory, we’ll create a public_html directory that will be the domain document root directory and will store the domain website files.
    Let’s start by creating the root directory for our domain example.com:

    sudo mkdir -p /var/www/example.com/public_html
    

    For testing purposes, we will create an index.html file inside the domain’s document root directory.
    Open your text editor and create the demo index.html file:

    sudo nano /var/www/example.com/public_html/index.html
    

    Copy and paste the following code into the file:

    /var/www/example.com/public_html/index.html
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>Welcome to example.com</title>
      </head>
      <body>
        <h1>Success! example.com home page!</h1>
      </body>
    </html>
    

    In this example, we are running the commands as a sudo user and the newly created files and directories are owned by the root user.
    To avoid any permission issues, change the ownership of the domain document root directory to the Nginx user (nginx):

    sudo chown -R nginx: /var/www/example.com
    

    2)Create a Server Block

    Nginx server block configuration files must end with .conf and are stored in /etc/nginx/conf.d directory.
    Open your editor of choice and create a server block configuration file for example.com.

    sudo nano /etc/nginx/conf.d/example.com.conf
    

    You can name the configuration file as you want. Usually, it is best to use the domain name.
    Copy and paste the following code into the file:

    /etc/nginx/conf.d/example.com.conf
    server {
        listen 80;
        listen [::]:80;
    
        root /var/www/example.com/public_html;
    
        index index.html;
    
        server_name example.com www.example.com;
    
        access_log /var/log/nginx/example.com.access.log;
        error_log /var/log/nginx/example.com.error.log;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

    Save the file and test the Nginx configuration for correct syntax:

    sudo nginx -t
    

    If there are no errors, the output will look like this:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

    Restart the Nginx service for the changes to take effect:

    sudo systemctl restart nginx
    

    Finally, to verify the server block is working as expected open http://example.com in your browser of choice, and you will see something like this:

    Conclusion

    You have learned how to create an Nginx server block configuration to host multiple domains on a single CentOS server. You can repeat the steps we outlined above and create additional server blocks for all your domains.

    4.Redirect HTTP to HTTPS in Nginx

    In this guide, we will explain how to redirect the HTTP traffic to HTTPS in Nginx.
    Nginx pronounced “engine x” is a free, open-source, high-performance HTTP and reverse proxy server responsible for handling the load of some of the largest sites on the Internet.
    If you are a developer or system administrator, chances are that you’re dealing with Nginx on a regular basis. One of the most common tasks you’ll likely perform is redirecting the HTTP traffic to the secured (HTTPS) version of your website.
    Unlike HTTP, where requests and responses are sent and returned in plaintext, HTTPS uses TLS/SSL to encrypt the communication between the client and the server.
    There are many benefits of using HTTPS over HTTP, such as:

    • All the data is encrypted in both directions. As a result, sensitive information cannot be read if intercepted.
    • Google Chrome and all other popular browsers will mark your website as safe.
    • HTTPS allows you to use the HTTP/2 protocol, which significantly improves the site performance.
    • Google favors HTTPS websites. Your site will rank better if served via HTTPS.
      The preferred method to redirect HTTP to HTTPS in Nginx is to configure a separate server block for each version of the site. You should avoid redirecting the traffic using the if directive , as it may cause unpredictable behavior of the server.

    1)Redirect HTTP to HTTPS per Site

    Typically when an SSL certificate is installed on a domain, you will have two server blocks for that domain. The first one for the HTTP version of the site on port 80, and the other for the HTTPS version on port 443.
    To redirect a single website to HTTPS open the domain configuration file and make the following changes:

    server {
        listen 80;
        server_name linuxize.com www.linuxize.com;
        return 301 https://linuxize.com$request_uri;
    }
    

    Let’s break down the code line by line:

    • listen 80 - The server block will listen for incoming connections on port 80 for the specified domain.
    • server_name linuxize.com www.linuxize.com - Specifies the server block’s domain names. Make sure you replace it with your domain name.
    • return 301 https://linuxize.com$request_uri - Redirect the traffic to the HTTPS version of the site. The $request_uri variable is the full original request URI, including the arguments.
      Usually, you will also want to redirect the HTTPS www version of the site to the non-www or vice versa. The recommended way to do the redirect is to create a separate server block for both www and non-www versions.
      For example, to redirect the HTTPS www requests to non-www, you would use the following configuration:
    server {
        listen 80;
        server_name linuxize.com www.linuxize.com;
        return 301 https://linuxize.com$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name www.linuxize.com;
    
        # . . . other code
    
        return 301 https://linuxize.com$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name linuxize.com;
    
        # . . . other code
    }
    

    Whenever you make changes to the configuration files you need to restart or reload the Nginx service for changes to take effect:

    sudo systemctl reload nginx
    

    2)Redirect All Sites to HTTPS

    If all of the websites hosted on the server are configured to use HTTPS, and you don’t want to create a separate HTTP server block for each site, you can create a single catch-all HTTP server block. This block will redirect all HTTP requests to the appropriate HTTPS blocks.
    To create a single catch-all HTTP block which will redirect the visitors to the HTTPS version of the site, open the Nginx configuration file and make the following changes:

    server {
    	listen 80 default_server;
    	listen [::]:80 default_server;
    	server_name _;
    	return 301 https://$host$request_uri;
    }
    

    Let’s analyze the code line by line:

    • listen 80 default_server - Sets this server block as the default (catch-all) block for all unmatched domains.
    • server_name _ - _ is an invalid domain name that never matches any real domain name.
    • return 301 https://$host$request_uri - Redirect the traffic to the corresponding HTTPS server block with status code 301 (Moved Permanently). The $host variable holds the domain name of the request.
      For example, if the visitor opens http://example.com/page2 in the browser, Nginx will redirect the request to https://example.com/page2.
      If possible, prefer creating a redirection on a per-domain basis instead of a global HTTP to HTTPS redirection.

    Conclusion

    In Nginx, the preferred way to redirect HTTP to HTTPS is to create a separate server blocks and perform 301 redirect.

    5.How to Enable the EPEL repository on CentOS

    The EPEL (Extra Packages for Enterprise Linux) repository provides additional software packages that are not included in the standard Red Hat and CentOS repositories. EPEL repository was created because Fedora contributors wanted to use the packages they maintain on Red Hat Enterprise Linux (RHEL) and its derivatives such as CentOS, Oracle Linux, and Scientific Linux.
    Enabling this repository gives you access to popular software packages including Nginx, R , and Python Pip.
    In this tutorial, we will show you how to enable the EPEL repository on CentOS.

    Prerequisites

    Before starting with the tutorial, make sure you are logged in as a user with sudo privileges.

    1)Enabling the EPEL Repository on CentOS 7

    Enabling the EPEL repository on CentOS 7 is a pretty simple task as the EPEL rpm package is included in the CentOS extras repository.
    To install the EPEL release package, type the following command:

    sudo yum install epel-release
    

    To verify that the EPEL repository is enabled run the yum repolist command that will list all available repositories.

    sudo yum repolist
    

    The command will display the repo ID, name and the number of packages for the enabled repositories. The output should include a line for the EPEL repository.

    Loaded plugins: fastestmirror, langpacks
    Loading mirror speeds from cached hostfile
    ...
    repo id             repo name                                         status
    base/7/x86_64       CentOS-7 - Base                                   10,019
    epel/x86_64         Extra Packages for Enterprise Linux 7 - x86_64    12,912
    extras/7/x86_64     CentOS-7 - Extras                                    371
    updates/7/x86_64    CentOS-7 - Updates                                 1,098
    repolist: 24,400
    

    That’s it. EPEL repository has been enabled on your CentOS system.

    2)Enabling the EPEL Repository on RHEL

    This method will work on any RHEL based distribution including Red Hat, CentOS 6 and 7, Oracle Linux, Amazon Linux, and Scientific Linux.
    To enable the EPEL repository, run the following command which will download and install the EPEL release package:

    sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$(rpm -E '%{rhel}').noarch.rpm
    

    rpm -E '%{rhel}' will print the distribution version (6 or 7).

    Conclusion

    For more information about the EPEL repository, see the EPEL documentation .

    6. Nginx Commands

    In this guide, we will go over the most important and frequently used Nginx commands, including starting, stopping, and restarting Nginx.

    Before You Begin

    We’re assuming that you are logged in as root or user with sudo privileges. The commands in uide this gshould work on any modern Linux distribution like Ubuntu 18.04 and CentOS 8 and Debian 10.

    Starting Nginx

    Starting Nginx is pretty simple. Just run the following command:

    sudo systemctl start nginx
    

    On success, the command doesn’t produce any output.
    If you are running a Linux distribution without systemd to start Nginx type:

    sudo service nginx start
    

    Instead of manually starting the Nginx service, it is recommended to set it to start on system boot:

    sudo systemctl enable nginx
    

    Stopping Nginx

    Stopping Nginx quickly shuts down all Nginx worker processes even if there are open connections.
    To stop Nginx, run one of the following commands:

    sudo systemctl stop nginxsudo service nginx stop
    

    Restarting Nginx

    The restart option is a quick way of stopping and then starting the Nginx server.
    Use one of the following commands to perform an Nginx restart:

    sudo systemctl restart nginxsudo service nginx restart
    

    This is the command that you will probably use the most frequently.

    Reloading Nginx

    You need to reload or restart Nginx whenever you make changes to its configuration.
    The reload command loads the new configuration, starts new worker processes with the new configuration, and gracefully shuts down old worker processes.
    To reload Nginx, use one of the following commands:

    sudo systemctl reload nginxsudo service nginx reload
    

    Testing Nginx Configuration

    Whenever you make changes to the Nginx server’s configuration file, it is a good idea to test the configuration before restarting or reloading the service.
    Use the following command to test the Nginx configuration for any syntax or system errors:

    sudo nginx -t
    

    The output will look like below:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

    If there are any errors, the command prints a detailed message.

    Viewing Nginx Status

    To check the status of the Nginx service, use the following command:

    sudo systemctl status nginx
    

    The output will look something like this:

    nginx.service - A high performance web server and a reverse proxy server
       Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
       Active: active (running) since Tue 2020-05-4 13:57:01 PDT; 5min ago
         Docs: man:nginx(8)
      Process: 4491 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
      Process: 4502 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
      Process: 4492 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
     Main PID: 4504 (nginx)
        Tasks: 3 (limit: 2319)
       CGroup: /system.slice/nginx.service
               |-4504 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
               |-4516 nginx: worker process
               `-4517 nginx: worker process
    

    Checking Nginx Version

    Sometimes you may need to know the version of your Nginx so you can debug an issue or determine whether a certain feature is available.
    You can check your Nginx version by running:

    sudo nginx -v
    nginx version: nginx/1.14.0 (Ubuntu)
    

    The -V option displays the Nginx version along with the configure option.

    sudo nginx -V
    

    Conclusion

    In this guide, we have shown you some of the most essential Nginx commands. If you want to learn more about the Nginx command line options, visit the Nginx documentation.

    posted in Tutorials & How To •
    How to Install Nginx on CentOS 7

    Introduction

    Nginx pronounced engine x is a free, open-source, high-performance HTTP and reverse proxy server responsible for handling the load of some of the largest sites on the Internet.
    Nginx can be used as a standalone web server, and as a reverse proxy for Apache and other web servers.

    Compared to Apache, Nginx can handle a much large number of concurrent connections and has a smaller memory footprint per connection.
    This tutorial will teach you how to install and manage Nginx on your CentOS 7 machine.


    Prerequisites

    • Deploy a Cybree Instance with CentOS 7 image.
    • Connect to your instance via Cybree VNC terminal, or use other terminal (such as Putty SSH) to connect your instance
    • Login to account with sudo or root privileges. The default Centos administrator login name is "root"
    • You don’t have Apache or any other service running on port 80 or 443.

    Step 1: Update Package Repository Cache

    • Before you start building the stack, be sure to update the packages on your CentOS 7 server using the command:
    sudo yum update
    
    • Enter "y" when you are prompted to confirm the installation. And wait a few minute to download and process until it prompts "Complete!"

    Step 2: Install Nginx

    1. Nginx packages are available in the EPEL repositories. If you don’t have EPEL repository already installed you can do it by typing:
    sudo yum install epel-release
    
    1. Install Nginx by typing the following yum command:
    sudo yum install nginx
    
    1. If this is the first time you are installing a package from the EPEL repository, yum may prompt you to import the EPEL GPG key. If that’s the case, type y and hit Enter.
    Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
    Importing GPG key 0x352C64E5:
    Userid     : "Fedora EPEL (7) <epel@fedoraproject.org>"
    Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
    Package    : epel-release-7-9.noarch (@extras)
    From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
    Is this ok [y/N]:
    
    1. Once the installation is complete, enable and start the Nginx service with:
    sudo systemctl enable nginx
    sudo systemctl start nginx
    
    1. Check the status of the Nginx service with the following command:
    sudo systemctl status nginx
    
    1. The output should look something like this:
    nginx.service - The nginx HTTP and reverse proxy server
       Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
       Active: active (running) since Thu 2021-05-06 15:17:17 JST; 4min 35s ago
      Process: 393 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
      Process: 390 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
      Process: 388 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
     Main PID: 396 (nginx)
       CGroup: /system.slice/nginx.service
               ├─396 nginx: master process /usr/sbin/nginx
               └─397 nginx: worker process
    
    1. To verify your Nginx installation, open http://YOUR_IP in your browser of choice, and you will see the default Nginx welcome page as shown in the image below:

    截屏2021-07-01 上午11.37.58.png

    Manage the Nginx Service with systemctl

    1. You can manage the Nginx service in the same way as any other systemd unit.
      To stop the Nginx service, run:
    sudo systemctl stop nginx
    
    1. To start it again, type:
    sudo systemctl start nginx
    
    1. To restart the Nginx service :
    sudo systemctl restart nginx
    
    1. Reload the Nginx service after you have made some configuration changes:
    sudo systemctl reload nginx
    
    1. If you want to disable the Nginx service to start at boot:
    sudo systemctl disable nginx
    
    1. And to re-enable it again:
    sudo systemctl enable nginx
    

    Nginx Configuration File’s Structure and Best Practices

    • All Nginx configuration files are located in the /etc/nginx/ directory.

    • The main Nginx configuration file is /etc/nginx/nginx.conf.

    • To make Nginx configuration easier to maintain it is recommended to create a separate configuration file for each domain.

    • New Nginx server block files must end with .conf and be stored in /etc/nginx/conf.d directory. You can have as many server blocks as you need.

    • It is a good idea to follow a standard naming convention, for example if your domain name is mydomain.com then your configuration file should be named /etc/nginx/conf.d/mydomain.com.conf

    • If you use repeatable configuration segments in your domains server blocks then it is a good idea to create a directory named /etc/nginx/snippets refactoring those segments into snippets and include the snippet file to the server blocks.

    • Nginx log files (access.log and error.log) are located in the /var/log/nginx/ directory. It is recommended to have a different access and error log files for each server block.

    • You can set your domain document root directory to any location you want. The most common locations for webroot include:
      o/home/<user_name>/<site_name>
      o/var/www/<site_name>
      o/var/www/html/<site_name>
      o/opt/<site_name>
      o/usr/share/nginx/html


    Conclusion

    Congratulations, you have successfully installed Nginx on your CentOS 7 server. You’re now ready to start deploying your applications and use Nginx as a web or proxy server. If you intend to host multiple domains on your CentOS server, you should learn how to create Nginx server blocks.

    posted in Tutorials & How To •