Empowering you with the knowledge to master Linux web hosting, DevOps and Cloud

 Linux Web Hosting, DevOps, and Cloud Solutions

Tag: Ubuntu Page 1 of 2

How to Share Files Between a Hyper-V Windows Host and Ubuntu guest VM

Introduction

Sharing files between a Windows host and Ubuntu virtual machine (VM) can be essential when you need to transfer data or collaborate between different environments. While the Hyper-V virtualization platform makes it easy to create Ubuntu VMs on a Windows host, the process of sharing files between the two systems can be a bit more complex. This is because Windows and Ubuntu use different file systems and protocols to access shared resources.

In this blog post, we will walk you through the steps required to share files between a Hyper-V Windows host and Ubuntu VM using the Common Internet File System (CIFS) protocol. This method allows you to mount a Windows shared folder on Ubuntu, giving you access to files on the Windows host as if they were on the Ubuntu machine itself. We will also cover the process of setting up a new Windows local user for authentication, creating a shared folder, and enabling network settings in Hyper-V. By the end of this guide, you will have a fully functional file sharing system that works seamlessly between Windows and Ubuntu.

1. Create a new Windows local user for sharing and authentication
To access a Windows shared folder from Ubuntu, you need to provide valid credentials for a user account that has permissions to access the shared folder. For security reasons, it’s not recommended to use your Windows user account for this purpose, as it could potentially expose your system to security risks. Instead, it’s best to create a new local user account that’s dedicated solely to file sharing.

Step-by-step guide for creating a new user in Windows
1. Press “Windows Key + R” on your keyboard to open the Run dialog box.
2. Type “netplwiz” in the box and click on “OK.”
3. In the User Accounts window that appears, click on the “Add” button.

4. Select “Sign in without a Microsoft account (not recommended)” at the bottom of the screen.
5. Click on “Local account” and then click on “Next.”
6. Enter a username and password for the new user and then click on “Next.”
7. You can choose whether to set a password hint for the new user account or not. Click on “Next” to proceed.
8. Click on “Finish” to complete the process.

I have created a user called “shareuser” with password as 123456. But please always use stronger password. Mine is just a test environment.

2. Create a Windows folder and enable sharing
In this step, we will create a new folder in Windows and enable sharing so that it can be accessed from our Ubuntu VM.

1. Open File Explorer and navigate to the location where you want to create a new folder.
2. Right-click on the empty space and select “New” > “Folder”.
3. Name the folder and press “Enter” on your keyboard.
4. Right-click on the newly created folder and select “Properties”.
5. In the Properties window, click on the “Sharing” tab.
6. Click on the “Share” button.
7. In the “Choose People to Share With” window, enter the name of the user you created earlier (e.g. “shareuser”).

8. Click on “Add” and then click on the “Share” button.
9. The folder should now be shared with the user you specified.

Note: If you don’t see the “Sharing” tab in the folder properties window, you may need to enable file and printer sharing in Windows by going to “Control Panel” > “Network and Sharing Center” > “Change advanced sharing settings” and selecting “Turn on file and printer sharing”. And I will be replacing the hostname “WAHAB” with an IP address in later stages.

Once you have shared the folder with the user, you can access it from your Ubuntu VM using the SMB protocol.

3. Enable default or external type network for VMs in Hyper-V
By default, the virtual machines are connected to the “Default Switch”. To communicate between the host and guest VM, you need to either use this default switch or external type virtual switch. If Private network type switch are used the Windows host will not be able to communicate or transfer files with guest VMs.

1. Open the Hyper-V Manager on the Windows host machine.
2. Select the virtual machine you want to connect to the network.
3. In the right-hand pane, click on “Settings”.
4. Click on “Network Adapter” and select “Virtual Switch” as the connection type.
5. Select either the “Default Switch” or an “External” virtual switch that you have previously created.
6. Click “OK” to save changes.
7. Start the virtual machine.

4. Find the private IP of Windows HyperV host
The private IP of the Windows host is needed to establish a connection between the Windows host and the Ubuntu VM. In order for the Ubuntu VM to access files on the Windows host, it needs to know the private IP address of the host so that it can connect to it over the network

1. Open the Command Prompt on the Windows host machine by pressing the Windows key + R and then typing “cmd” in the Run dialog box.
2. In the Command Prompt, type “ipconfig” and press Enter.
3. Look for the IPv4 Address entry. The number listed next to this entry is the private IP address of the Windows host.
Note: The private IP address is usually in the format of “192.168.x.x” or “172.x.x.x”.

5. Check folder shared is accessible using smbclient from Ubuntu VM

smbclient is a command-line tool used to connect to Windows and Samba file servers. It allows us to browse and manipulate files and directories on remote servers using the Server Message Block (SMB) protocol.

In this step, we will use smbclient to verify if the shared folder is accessible from the Ubuntu VM.

Step-by-step guide for checking if the share is accessible using smbclient:

1. Open the terminal on Ubuntu VM.
2. Install smbclient if it’s not installed using the following command:

sudo apt-get install smbclient

3. Connect to the shared folder using the following command:

smbclient -U shareuser //172.30.96.1/FolderToShare

Note: Replace “shareuser” with the username of the Windows local user you created and “FolderToShare” with the name of the shared folder you created
4. Enter the password for the Windows local user when prompted.
5. If the connection is successful, you should see a prompt like this:

6. Mount the Windows share using cifs
CIFS (Common Internet File System) is a network protocol that allows Linux systems to access and share files and directories with Windows operating systems. It is needed to mount the Windows share on the Ubuntu VM so that the Ubuntu user can access the shared files and directories.

Here are the step-by-step instructions for mounting the Windows share using cifs:

Create a directory where you want to mount the Windows share. For example, let’s create a directory called “windows_share” under the home directory:

mkdir ~/windows_share

Install the cifs-utils package if it’s not already installed on the Ubuntu VM:

sudo apt-get update
sudo apt-get install cifs-utils

Create a file and add the Windows user credentials in it.

nano /home/wahab/.smbcredentials

username=shareuser
password=123456

Replace “shareuser” with the username you created for file sharing on your Windows host.
Replace “123456” with the password you set for the user.

Open the “/etc/fstab” file using a text editor with root privileges, such as nano:

sudo nano /etc/fstab

Add the following line at the end of the file:

//172.30.96.1/FolderToShare /home/wahab/windows_share cifs credentials=/home/wahab/.smbcredentials,uid=wahab,gid=wahab 0 0

Replace “172.30.96.1” with your Windows host IP address.
Replace “FolderToShare” with the name of the shared folder on your Windows host.
“/home/wahab/windows_share” will be the folder you mounting your Windows share. So you may choose different one as per your need.
The “uid” and “gid” options set the ownership of the mounted directory to the Ubuntu user “wahab”, replace them with yours.
The “0 0” options indicate that the filesystem should be dumped and checked by default.
Save and close the file.

Here’s how to mount and unmount the Windows share as the Ubuntu user “wahab”:

To mount the share:

sudo mount ~/windows_share

Check if the Windows share is mounted by running a “df -h” command

To unmount the share:

sudo umount ~/windows_share

In conclusion, sharing files between a Windows host and Ubuntu VM can be accomplished through the use of the Common Internet File System (CIFS) protocol. The process involves creating a new Windows local user for sharing and authentication, creating a Windows folder and enabling sharing, and configuring the network settings in Hyper-V. Once these steps are completed, you can easily access the shared folder from your Ubuntu VM as if it were on the local machine. It’s important to ensure that you follow security best practices by using a dedicated user account for file sharing and setting a strong password. With these steps, you can establish a seamless and secure file sharing system between Windows and Ubuntu.

Installing PHP GEOS module on a RunCloud Server

PHP GEOS is a PHP extension for geographic objects support, while RunCloud is a cloud server control panel designed for PHP applications. With PHP GEOS module installed on RunCloud, PHP applications can take advantage of geographic data and use the GEOS (Geometry Engine – Open Source) library to perform spatial operations.

In this blog post, I will show you how to install PHP GEOS module on RunCloud module.

Steps
1. Install the required development tools

Before installing the PHP GEOS module, make sure that the required development tools are installed on your Ubuntu server. You can install them by running the following command:

apt-get install autoconf

2. Install GEOS library
Next, download and install the latest GEOS (Geometry Engine – Open Source)

wget http://download.osgeo.org/geos/geos-3.9.4.tar.bz2
tar xvf geos-3.9.4.tar.bz2
cd geos-3.9.4/
./configure
make
make install

3. Install PHP GEOS module

Now, it’s time to install the PHP GEOS module. Follow the steps below to install it for PHP 8.2:

# Set module name
MODULE_NAME="geos"

Download the latest module files

git clone https://git.osgeo.org/gitea/geos/php-geos.git
mv php-geos/ php-geos_PHP82

# make clean will always fail if you never compile it before
make clean
/RunCloud/Packages/php82rc/bin/phpize --clean
/RunCloud/Packages/php82rc/bin/phpize
./configure --with-php-config=/RunCloud/Packages/php82rc/bin/php-config
make && make install

This will install geos.so in the correct php extension directory

4. Add the module to PHP.ini file
echo "extension=$MODULE_NAME.so" > /etc/php82rc/conf.d/$MODULE_NAME.ini

And finally restart the PHP FPM service
systemctl restart php82rc-fpm

It’s important to note that the above steps are specific to PHP 8.2. If you wish to install the module for a different version, you will need to modify the commands accordingly. For instance, you can replace PHP 8.2 with 8.1 with below changes:
Replace /RunCloud/Packages/php82rc/bin/phpize with /RunCloud/Packages/php81rc/bin/phpize, replace ./configure –with-php-config=/RunCloud/Packages/php82rc/bin/php-config with ./configure –with-php-config=/RunCloud/Packages/php81rc/bin/php-config, replace /etc/php82rc/conf.d/$MODULE_NAME.ini with /etc/php81rc/conf.d/$MODULE_NAME.ini, and replace systemctl restart php82rc-fpm with systemctl restart php81rc-fpm.

You can contact me if you need help with installing any custom modules on RunCloud control panel.

Downgrading PHP Version on Bitnami WordPress in AWS Lightsail instance

Hi all

Recently, I helped one of my clients who was using an Amazon Lightsail WordPress instance provided by Bitnami. Bitnami is advantageous in that it provides a fully working stack, so you don’t have to worry about configuring LAMP or environments. You can find more information about the Bitnami Lightsail stack here.

However, the client’s stack was using the latest PHP 8.x version, while the WordPress site he runs uses several plugins that need PHP 7.4. I advised the client to consider upgrading the website to support the latest PHP versions. However, since that would require a lot of work, and he wanted the site to be up and running, he decided to downgrade PHP.

The issue with downgrading or upgrading PHP on a Bitnami stack is that it’s not possible. Bitnami recommends launching a new server instance with the required PHP, MySQL, or Apache version and migrating the data over. So, I decided to do it manually.

Here are the server details:

Debian 11
Current installed PHP: 8.1.x

Upgrading or downgrading PHP versions on a Bitnami stack is essentially the same as on a normal Linux server. In short, you need to:

Ensure the PHP packages for the version you want are installed.
Update any configuration for that PHP version.
Update your web server configuration to point to the correct PHP version.
Point PHP CLI to the correct PHP version.
Restart your web server and php-fpm.

What we did was install the PHP version provided by the OS. Then, we updated php.ini to use the non-default MySQL socket location used by the Bitnami server. We created a php-fpm pool that runs as the “daemon” user. After that, we updated the Apache configuration to use the new PHP version.

1. Make sure packages for your target version of PHP are installed
To make sure that the correct packages are available on your system for the PHP version you want, first make sure your system is up to date by running these commands:

sudo apt update
sudo apt upgrade
If it prompts you to do anything with config files, usually, you should just go with the default option and leave the current config as-is. Then, install the packages you need. For example, you can use the following command to install common PHP packages and modules:
sudo apt install -y php7.4-cli php7.4-dev php7.4-pgsql php7.4-sqlite3 php7.4-gd php7.4-curl php7.4-memcached php7.4-imap php7.4-mysql php7.4-mbstring php7.4-xml php7.4-imagick php7.4-zip php7.4-bcmath php7.4-soap php7.4-intl php7.4-readline php7.4-common php7.4-pspell php7.4-tidy php7.4-xmlrpc php7.4-xsl php7.4-fpm

2. Make sure PHP configuration for your target version is updated
Find the mysql socket path used by your Bitnami stack by running this command:

# ps aux | grep –color mysql.sock
mysql 7700 1.1 2.0 7179080 675928 ? Sl Mar21 11:21 /opt/bitnami/mariadb/sbin/mysqld –defaults-file=/opt/bitnami/mariadb/conf/my.cnf –basedir=/opt/bitnami/mariadb –datadir=/bitnami/mariadb/data –socket=/opt/bitnami/mariadb/tmp/mysql.sock –pid-file=/opt/bitnami/mariadb/tmp/mysqld.pid

Edit php.ini file

vi /etc/php/7.4/fpm/php.ini

Find

[Pdo_mysql]
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
pdo_mysql.default_socket=

Replace with

[Pdo_mysql]
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
pdo_mysql.default_socket= “/opt/bitnami/mariadb/tmp/mysql.sock”

Find

mysqli.default_socket =

Replace with

mysqli.default_socket = “/opt/bitnami/mariadb/tmp/mysql.sock”

Create a php-fpm pool file

vi /etc/php/8.1/fpm/pool.d/wp.conf

[wordpress]
env[PATH] = $PATH
listen=/opt/bitnami/php/var/run/www2.sock
user=daemon
group=daemon
listen.owner=daemon
listen.group=daemon
pm=dynamic
pm.max_children=400
pm.start_servers=260
pm.min_spare_servers=260
pm.max_spare_servers=300
pm.max_requests=5000

Feel free to adjust the PHP FPM settings to match your server specifications or needs. Check out this informative article for more tips on optimizing PHP FPM performance. Just keep in mind that Bitnami configures their stack with the listen.owner and listen.group settings set to daemon.

This pool will listen on unix socket “/opt/bitnami/php/var/run/www2.sock”.

Enable and restart PHP 8.1 fpm service

systemctl enable php7.4-fpm
systemctl restart php7.4-fpm

3. Update your web server configuration to point to the correct PHP version

Edit file

vi /opt/bitnami/apache2/conf/bitnami/php-fpm.conf

For some installations, file is located at

vi /opt/bitnami/apache2/conf/php-fpm-apache.conf

Inside you file find



SetHandler “proxy:fcgi://www-fpm”

Find and replace www.sock with www2.sock

4. Make sure PHP-CLI points to the right PHP version

Rename the default PHP installed by bitnami.

mv /opt/bitnami/php/bin/php /opt/bitnami/php/bin/php_8.1_bitnami.

create a symlink from newly installed PHP 7.4

ln -s /usr/bin/php7.4 /opt/bitnami/php/bin/php

Test the installed version by running below command
~# php -v
PHP 7.4.33 (cli) (built: Feb 22 2023 20:07:47) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.33, Copyright (c), by Zend Technologies

5. Restart PHP-FPM and your webserver

sudo systemctl restart php7.4-fpm; sudo /opt/bitnami/ctlscript.sh restart apache

How to install Redmine on Ubuntu 22.04 with Apache and SSL


How to install Redmine on Ubuntu 22.04

Introduction
Redmine is a powerful and versatile project management tool that can help teams stay organized, collaborate effectively, and track progress towards their goals. Originally developed for the Ruby on Rails community, Redmine is now used by thousands of organizations worldwide, from small startups to large enterprises.

With Redmine, you can create projects and sub-projects, define tasks and issues, assign them to team members, set due dates and priorities, and track time spent on each task. You can also add comments and attachments to issues, create custom fields and workflows, and generate reports and graphs to visualize project status and progress.

It is open-source software written in Ruby on Rails and is available under the GNU General Public License.

Whether you’re a software development team, a marketing agency, a non-profit organization, or any other type of group that needs to manage projects and tasks, Redmine can be a valuable tool to help you stay on track, collaborate effectively, and achieve your goals. In this blog, we’ll explore some of the key features and use cases of Redmine, and provide tips and best practices for getting the most out of this powerful project management tool.

In this tutorial, we will go through the steps of installing Redmine on an Ubuntu 22.04 server and secure it Let’s Encrypt SSL.

Prerequisites:

Ubuntu 22.04 Server
Root or sudo user access
A domain name pointed to the server is required for accessing Redmine via a web browser.

Step 1: Update Ubuntu System
The first step is to update the Ubuntu system to ensure that all the packages are up-to-date. You can do this by running the following command:
sudo apt update
Step 2: Install Dependencies
Redmine requires several dependencies to be installed before it can be installed. To install them, run the following command:

sudo apt install -y build-essential libmagickwand-dev libxml2-dev libxslt1-dev libffi-dev libyaml-dev zlib1g-dev libssl-dev git imagemagick libcurl4-openssl-dev libtool libxslt-dev ruby ruby-dev rubygems libgdbm-dev libncurses-dev

Also, install Apache and Apache mod Passenger module
sudo apt install -y apache2 libapache2-mod-passenger

Note: libapache2-mod-passenger is a module for the Apache web server that enables the deployment of Ruby on Rails web applications. It provides an easy way to configure and manage Ruby on Rails applications within an Apache web server environment.

Step 3: Create a Redmine User
Create a dedicated Linux user for running Redmine:
useradd -r -m -d /opt/redmine -s /usr/bin/bash redmine

Add the user to the www-data group to enable Apache to access Redmine files:
usermod -aG redmine www-data

Step 4: Install and Secure MariaDB
MariaDB is a popular open-source database management system and is used as the backend for Redmine. To install and secure MariaDB, run the following commands:
sudo apt install -y mariadb-server

Enable and run the database service.

systemctl enable --now mariadb
mysql_secure_installation

Note: mysql_secure_installation is used to secure the installation by performing a series of security-related tasks, such as:

  • Setting a root password for the MySQL or MariaDB server.
  • Removing the anonymous user accounts, which are accounts without a username or password.
  • Disabling remote root logins, which can be a security vulnerability.
  • Removing the test database, which is a sample database that is not needed for most production environments.
  • Reloading the privilege tables to ensure that the changes take effect.

    Create a database and User. Replace the names of the database and the database user accordingly.

    mysql -u root -p
    create database redminedb;
    grant all on redminedb.* to redmineuser@localhost identified by 'P@ssW0rD';

    Reload privilege tables and exit the database.

    flush privileges;
    quit

    Step 5: Download and Extract Redmine
    Download the latest version of Redmine and extract it to the /opt/redmine directory using the following command:

    curl -s https://www.redmine.org/releases/redmine-5.0.5.tar.gz | sudo -u redmine tar xz -C /opt/redmine/ --strip-components=1

    Create Redmine configuration file by renaming the sample configuration files as shown below;

    su - redmine
    cp /opt/redmine/config/configuration.yml{.example,}
    cp /opt/redmine/public/dispatch.fcgi{.example,}
    cp /opt/redmine/config/database.yml{.example,}

    The sample configuration files are provided by Redmine as a starting point for configuring your installation.

    Step 6: Configure the Database
    Modify the config/database.yml file and update database name, username, and password for the production environment:

    nano /opt/redmine/config/database.yml
    In the file, replace the default configuration with the following:

    production:
      adapter: mysql2
      database: redminedb
      host: localhost
      username: redmineuser
      password: "P@ssW0rD"
      encoding: utf8mb4
    

    Since the configuration file is an yaml, you need to use proper Indentation.

    Save and close the file.

    Step 7: Install Bundler and Redmine Dependencies
    Install Bundler for managing gem dependencies and run the following commands:

    sudo gem install bundler

    Login as redmine user and execute below commands:

    su - redmine
    bundle config set --local without 'development test'
    bundle install
    bundle update
    exit

    Step 8: Configure File System Permissions
    Ensure that the following directories are available in the Redmine directory (/opt/redmine):

    tmp and tmp/pdf
    public and public/plugin_assets
    log
    files

    Create them if they don’t exist and ensure that they are owned by the user used to run Redmine:

    for i in tmp tmp/pdf public/plugin_assets; do [ -d $i ] || mkdir -p $i; done
    chown -R redmine:redmine files log tmp public/plugin_assets
    chmod -R 755 /opt/redmine

    Step 9: Configure Apache
    Create a new Apache virtual host file for Redmine:
    sudo nano /etc/apache2/sites-available/redmine.conf

    Paste the following configuration into the file:

    <VirtualHost *:80>
        ServerName redmine.linuxwebhostingsupport.in
        DocumentRoot /opt/redmine/public
        ErrorLog ${APACHE_LOG_DIR}/redmine-error.log
        CustomLog ${APACHE_LOG_DIR}/redmine-access.log combined
        <Directory /opt/redmine/public>
            Require all granted
            Options -MultiViews
            PassengerEnabled on
            PassengerAppEnv production
            PassengerRuby /usr/bin/ruby
        </Directory>
    </VirtualHost>
    

    Save the file and exit the text editor. Replace redmine.linuxwebhostingsupport.in with your domain name.

    Enable the Redmine site by running the following command:

    sudo a2ensite redmine.conf

    Restart Apache to apply the changes:

    sudo systemctl restart apache2

    Allow Apache through the Ubuntu UFW firewall:

    sudo ufw allow 'Apache Full'

    Install Certbot and the Apache plugin for Let’s Encrypt:

    sudo apt install certbot python3-certbot-apache

    Adding Lets Encrypt SSL certificate

    You need to make sure your domain is properly pointed to the server IP, otherwise, Let’s encrypt will fail.

    Obtain an SSL certificate for your domain by running the following command:

    sudo certbot --apache

    Follow the on-screen instructions to complete the process.

    Restart Apache to apply the SSL configuration:

    sudo systemctl restart apache2

    Open your web browser and go to https://redmine.linuxwebhostingsupport.in/. You should see the Redmine home screen.

    Login to the admin area using your Redmine admin username and password. If this is your first login, you will need to reset your admin password.

    https://redmine.linuxwebhostingsupport.in/login

    Congratulations! You have successfully installed and configured Redmine on your Ubuntu server. In the previous steps, we have covered the installation and configuration of Redmine, including setting up the database, configuring Apache, and securing Redmine with Let’s Encrypt SSL.


    However, one critical aspect of Redmine that you might want to configure is email delivery for notifications. This feature is essential for keeping team members informed about project updates, new issues, and changes to existing issues. In this section, we will show you how to configure email delivery in Redmine.

    Configuring SMTP for Email Delivery in Redmine

    Redmine supports email delivery for notifications, which you can set up using the following steps:

    Step 1 – Open Configuration File

    First, you need to open the configuration.yml file in a text editor:

    sudo nano /opt/redmine/config/configuration.yml

    Step 2 – Configure Email Settings

    Next, scroll down to the production section of the file, uncomment the following lines by removing the # symbol at the beginning of each line, and replace the values with your SMTP server’s settings:

    # specific configuration options for production environment
    # that overrides the default ones
    production:
      email_delivery:
        delivery_method: :smtp
        smtp_settings:
          address: "your.smtp.server.com"
          port: 587
          domain: "your.domain.com"
          authentication: :login
          user_name: "your_email@example.com"
          password: "your_email_password"
          enable_starttls_auto: true
    # specific configuration options for development environment
    # that overrides the default ones
    

    Replace the values for address, port, domain, user_name, and password with your SMTP server’s settings:

    address: The address of your SMTP server.
    port: The port number to use for SMTP server (usually 587).
    domain: The domain name of your organization or server.
    user_name: The email address of the user account to use for sending emails.
    password: The password for the user account to use for sending emails.
    Save the configuration.yml file.

    Since the configuration file is an yaml, you need to use proper Indentation.

    Step 3 – Restart Apache

    Finally, restart Apache to apply the changes:

    sudo systemctl restart apache2
    And that’s it! Redmine is now configured to deliver email notifications to your team members.

    Conclusion

    Redmine is a powerful project management tool that can help you manage your software development projects effectively. In this blog post, we have covered the installation and configuration of Redmine on Ubuntu, including setting up the database, configuring Apache, securing Redmine with Let’s Encrypt SSL, and configuring email delivery.

    With these steps, you should now have a working Redmine installation that can help you track your projects, collaborate with your team, and stay on top of your development process. Good luck!

  • Step-by-Step Tutorial: Setting up Apache, MySQL, PHP (LAMP Stack) on Ubuntu 22.04 for Beginners

    What is a LAMP Stack?

    LAMP stack is a popular combination of open-source software that is used to run dynamic websites and web applications. The acronym LAMP stands for Linux (operating system), Apache (web server), MySQL (database management system), and PHP (scripting language).

    Linux provides the foundation for the LAMP stack, serving as the operating system on which the other software components are installed. Apache is the web server that handles HTTP requests and serves web pages to users. MySQL is a powerful database management system that is used to store and manage website data. PHP is a popular scripting language used to create dynamic web content, such as interactive forms and web applications.

    Together, these software components create a powerful platform for building and deploying web applications. The LAMP stack is highly customizable and widely used, making it an excellent choice for developers and system administrators alike.

    Prerequisites

    1. Ubuntu server: You will need an Ubuntu server to install the LAMP stack. You can use a Virtual/CLoud server or a physical server as per your requirement.

    2. SSH access: You will need SSH access to your Ubuntu server to be able to install the LAMP stack. SSH (Secure Shell) is a secure network protocol that allows you to access and manage your server remotely.

    3. Non-root user with sudo privileges: It is recommended that you use a non-root user with sudo privileges to install and configure the LAMP stack. This is because running as root can pose a security risk and may lead to unintended consequences if something goes wrong. You can also run the commands as root user.

    4. Basic familiarity with Linux command line: A basic understanding of how to use the Linux command line interface (CLI) to run commands and navigate your Ubuntu server is recommended, not mandatory.

    Installing a LAMP Stack on Ubuntu
    In this section, the process of installing a LAMP Stack on Ubuntu 22.04 LTS is outlined. These instructions can be applied to Ubuntu 20.04 LTS as well.

    A LAMP stack is a popular combination of open-source software used to run dynamic websites or web applications. LAMP stands for Linux (operating system), Apache (web server), MySQL (database management system), and PHP (scripting language). In this guide, we will walk you through the steps involved in installing and configuring a LAMP stack on an Ubuntu server.

    Step 1: Update Your Ubuntu Server
    Before we begin installing LAMP stack components, let’s update the server’s software packages by running the following command:

    sudo apt update && sudo apt upgrade

    Step 2: Install Apache
    Apache is the most widely used web server software. To install it, run the following command:

    sudo apt install apache2

    Once the installation is complete, you can check the status of Apache by running the following command:

    sudo systemctl status apache2
    This will display Apache’s status as either active or inactive.

    Step 3: Install MySQL
    MySQL is a popular open-source database management system. To install it, run the following command:

    sudo apt install mysql-server
    Once the installation is complete, you can check the status of MySQL by running the following command:

    sudo systemctl status mysql
    This will display MySQL’s status as either active or inactive.

    Step 4: Install PHP
    PHP is a popular server-side scripting language used to create dynamic web content. To install it, run the following command:

    sudo apt install php libapache2-mod-php php-mysql

    There are several additional PHP modules recommended for a CMS like WordPress. You can install them by running the command below:
    sudo apt-get install php-curl php-gd php-xml php-mbstring php-imagick php-zip php-xmlrpc
    After installing these modules, you will need to restart your Apache server for the changes to take effect. You can do this by running the following command:

    sudo systemctl restart apache2

    Setting up firewall rules to allow access to Apache web server

    UFW is the default firewall with Ubuntu systems, providing a simple command-line interface to configure iptables, the software-based firewall used in most Linux distributions. UFW provides various application profiles that can be utilized to manage traffic to and from different services. To view a list of all the available UFW application profiles, you can run the command:

    sudo ufw app list

    Output
    Available applications:
    Apache
    Apache Full
    Apache Secure
    OpenSSH

    These application profiles have different configurations for opening specific ports on the firewall. For instance:

    Apache: Allows traffic on port 80, which is used for normal, unencrypted web traffic.
    Apache Full: Allows traffic on both port 80 and port 443, which is used for TLS/SSL encrypted traffic.
    Apache Secure: Allows traffic only on port 443 for TLS/SSL encrypted traffic.

    To allow traffic on both port 80 and port 443(SSL), you can use the Apache Full profile by running the following command:

    sudo ufw allow in "Apache Full"

    You can verify that the change has been made by running the command:
    sudo ufw status

    Output

    Status: active
    
    To                         Action      From
    --                         ------      ----
    OpenSSH                    ALLOW       Anywhere                                
    Apache Full                ALLOW       Anywhere                  
    OpenSSH (v6)               ALLOW       Anywhere (v6)                    
    Apache Full(v6)            ALLOW       Anywhere (v6)   
    

    To test if the ports are open and Apache web server is accessible, you can try visiting your server’s public IP address in a web browser using the URL http://your_server_ip. If successful, you should see the default Apache web page.

    If you can view this page, your web server is correctly installed and accessible through your firewall.

    Configuring the MySQL Database server
    Upon installation of MySQL, it is immediately available for use. However, in order to utilize it for web applications such as WordPress and improve the security of said applications, it is imperative to generate a database user and database. To complete the configuration process for MySQL, please adhere to the following steps.

    To configure MySQL and improve application security, follow these steps:

    1. Log in to the MySQL shell as the root user:

    sudo mysql -u root

    2. Using the MySQL shell, you can create the wpdatabase database and generate a new user account for accessing the web application. Instead of using the placeholders “dbuser” and “password” in the CREATE USER query, you should provide a real username and password. Furthermore, you should grant complete permissions to the user. After each line, MySQL should respond with “Query OK.”

    CREATE DATABASE wpdatabase ;
    CREATE USER 'dbuser' IDENTIFIED BY 'password';
    GRANT ALL ON wpdatabase .* TO 'dbuser';

    Exit the SQL shell:
    quit

    3. Set a password for root’@’localhost:

    sudo mysql
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'password';

    Exit the SQL shell:
    quit

    Note: Replace “password” with a strong password.
    4. Use the mysql_secure_installation tool to increase database security:

    sudo mysql_secure_installation

    When prompted to change the root password, leave it unchanged. Answer Y for the following questions:

    Remove anonymous users?
    Disallow root login remotely?
    Remove test database and access to it?
    Reload privilege tables now?

    To log in to the MySQL shell as root after this change, use “sudo mysql -u root” and type “quit” exit the SQL Shell.

    It’s worth noting that when connecting as the root user, there’s no need to enter a password, despite having defined one during the mysql_secure_installation script. This is due to the default authentication method for the administrative MySQL user being unix_socket rather than password. Although it may appear to be a security issue, it actually strengthens the security of the database server by only allowing system users with sudo privileges to log in as the root MySQL user from the console or through an application with the same privileges. As a result, you won’t be able to use the administrative database root user to connect from your PHP application. However, setting a password for the root MySQL account acts as a precautionary measure in case the default authentication method is changed from unix_socket to password.

    Creating a Virtual Host for your Website

    In order to host multiple domains from a single server, Apache web server provides the capability to create virtual hosts. These virtual hosts are beneficial as they allow you to encapsulate configuration details for each domain. In this tutorial, we will walk you through setting up a domain named “example.com”. However, it is important to keep in mind that you should replace “example.com” with your own domain name.

    By default, Ubuntu 22.04’s Apache web server has a single virtual host that is enabled and configured to serve documents from the /var/www/html directory. While this is a workable solution for a single site, it becomes cumbersome when hosting multiple sites. Therefore, instead of modifying /var/www/html, we will create a directory structure within the /var/www directory specifically for the example.com site. In doing so, we will leave /var/www/html in place as the default directory to be served if a client request does not match any other sites.

    1. First, create a new directory for the “example.com” website files:

    sudo mkdir /var/www/example.com

    2. Assign the ownership of the directory to the web server user (www-data):

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

    3. Create a new virtual host configuration file for “example.com” using the nano text editor:

    sudo nano /etc/apache2/sites-available/example.com.conf

    4. Add the following configuration to the file, replacing “example.com” with your own domain name:

    <VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/example.com
    
        <Directory /var/www/example.com>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>
    
        ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
        CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
    </VirtualHost>
    

    This configuration specifies that the “example.com” domain should use the files located in the /var/www/example.com directory as its document root.

    5. Disable the default Apache site configuration to avoid conflicts:

    sudo a2dissite 000-default.conf

    6. Enable the “example.com” site configuration:
    sudo a2ensite example.com.conf

    7. Restart Apache to apply the changes:
    sudo systemctl restart apache2

    8. Create a test “hello world” HTML file:
    sudo nano /var/www/example.com/index.html

    Add the following HTML code to the file:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <h1>Hello World!</h1>
    </body>
    </html>
    

    9. Save and close the file.

    10. Finally, configure your DNS records to point the “example.com” domain to your server’s IP address. Once the DNS records are updated, you can access the website by visiting “http://example.com” in your web browser.

    Testing the LAMP Stack Installation on Your Ubuntu Server
    To ensure that the LAMP stack configuration is fully functional, it’s necessary to conduct tests on Apache, PHP, and MySQL components. Verifying the Apache operational status and virtual host configuration was done earlier. Now, it’s important to test the interaction between the web server and PHP and MySQL components.

    The easiest way to verify the configuration of the Ubuntu LAMP stack is by using a short test script. The PHP code does not need to be lengthy or complex; however, it must establish a connection to MySQL. The test script should be placed within the DirectoryRoot directory.

    To validate the database, use PHP to invoke the mysqli_connect function. Use the username and password created in the “Configuring the MySQL Database server” section. If the attempt is successful, the mysqli_connect function returns a Connection object. The script should indicate whether the connection succeeded or failed and provide more information about any errors.

    To verify the installation, follow these steps:

    1. Create a new file called “phptest.php” in the /var/www/example.com directory.

    <html>
    <head>
        <title>PHP MySQL Test</title>
    </head>
        <body>
        <?php echo '<p>Welcome to the Site!</p>';
    
        // When running this script on a local database, the servername must be 'localhost'. Use the name and password of the web user account created earlier. Do not use the root password.
        $servername = "localhost";
        $username = "dbuser";
        $password = "password";
    
        // Create MySQL connection
        $conn = mysqli_connect($servername, $username, $password);
    
        // If the conn variable is empty, the connection has failed. The output for the failure case includes the error message
        if (!$conn) {
            die('<p>Connection failed: </p>' . mysqli_connect_error());
        }
        echo '<p>Connected successfully</p>';
        ?>
    </body>
    </html>
    

    2. To test the script, open a web browser and type the domain name followed by “/phptest.php” in the address bar. For example, if your domain name is “example.com”, you would enter “example.com/phptest.php” in the address bar. Make sure to substitute the actual name of the domain for “example.com” in the example provided.

    http://example.com/phptest.php

    3. Upon successful execution of the script, the web page should display without any errors. The page should contain the text “Welcome to the Site!” and “Connected successfully.” However, if you encounter the “Connection Failed” error message, review the SQL error information to troubleshoot the issue.

    Bonus: Install phpMyAdmin
    phpMyAdmin is a web-based application used to manage MySQL databases. To install it, run the following command:

    sudo apt install phpmyadmin
    During the installation process, you will be prompted to choose the web server that should be automatically configured to run phpMyAdmin. Select Apache and press Enter.

    You will also be prompted to enter a password for phpMyAdmin’s administrative account. Enter a secure password and press Enter.

    Once the installation is complete, you can access phpMyAdmin by navigating to http://your_server_IP_address/phpmyadmin in your web browser.

    Congratulations! You have successfully installed and configured a LAMP stack on your Ubuntu server.

    Summary
    This guide walks through the process of setting up a LAMP Stack, a combination of the Linux operating system, Apache web server, MySQL RDBMS, and PHP programming language, to serve PHP websites and applications. The individual components are free and open source, designed to work together, and easy to install and use. Following the steps provided, you can install the LAMP Stack on Ubuntu 22.04 LTS using apt, configure the Apache web server, create a virtual host for the domain, and integrate the MySQL web server by creating a new account to represent the web user. Additional PHP packages are required for Apache, PHP, and the database to communicate. A short PHP test script can be used to test the new installation by connecting to the database.

    How to remove or compress huge MySQL general and query log table

    How to remove or compress huge MySQL general and query log table

    If you have enabled MySQL general or slow logging, it can create quite big log, depending upon your MySQL usage/queries.
    So we may have to periodically clear them to save space.

    Please note that MySQL can save logs to either table or files. This document assumes you are using table as log output.

    Files: slow_log.CSV and general_log.CSV (The location and the name of the file can be different)

    By default, logging is to CSF file.

    MYSQL supports run time clearing of these logs. So no need to restart the MySQL service.
    Never delete the CSV file directly. It can crash MySQL.

    Slow query log

    SET GLOBAL slow_query_log='OFF';
    DROP TABLE IF EXISTS slow_log2;
    CREATE TABLE slow_log2 LIKE slow_log;
    RENAME TABLE slow_log TO slow_log_backup, slow_log2 TO slow_log;
    gzip /var/db/mysql/mysql/slow_log_backup.CSV 
    DROP TABLE  slow_log_backup;
    SET GLOBAL slow_query_log = 'ON';
    

    General log

    USE mysql;
    SET GLOBAL general_log = 'OFF';
    DROP TABLE IF EXISTS general_log2;
    CREATE TABLE general_log2 LIKE general_log;
    RENAME TABLE general_log TO general_log_backup, general_log2 TO general_log;
    gzip /var/db/mysql/mysql/general_log_backup.CSV 
    DROP TABLE  general_log_backup;
    

    What we did is create new log table, move current log file to a backup copy and compress the backup and remove it.

    Install Ajenti V on Ubuntu 16.04 on Ubuntu 16.04

    Install Ajenti v on Ubuntu 16.04

    Ajenti is an open source, web-based control panel that can be used for a large variety of server management tasks. Optionally, an add-on package called Ajenti V allows you to manage multiple websites from the same control panel


    Step 1: First make sure that all your system packages are up-to-date

    sudo apt-get update
    sudo apt-get upgrade

    Step 2: Installing Ajenti Control Panel.
    wget -O- https://raw.github.com/ajenti/ajenti/1.x/scripts/install-ubuntu.sh | sudo sh

    Step 3: Start the service:
    systemctl start ajenti

    Step4: Install Agenti hosting module + nginx+ mail+ftp

    If you have Apache installed, but don’t use it, remove it first:
    apt-get remove apache2

    If you have Sendmail or Postfix installed, remove them too
    apt-get remove sendmail postfix

    Install Ajenti-v

    apt-get install ajenti-v ajenti-v-nginx ajenti-v-mysql ajenti-v-php7.0-fpm php7.0-mysql

    # If you need Python
    apt-get install ajenti-v-python-gunicorn

    # If you want FTP
    apt-get install ajenti-v-ftp-pureftpd

    # If you want mail
    apt-get install ajenti-v-mail

    # If you want POP support (for gmail etc.)
    apt-get install courier-pop

    Step 5: Restart All Services
    systemctl restart nginx
    systemctl restart php7.0-fpm
    systemctl restart mysql
    systemctl restart exim4
    systemctl restart pure-ftpd
    systemctl restart ajenti

    Step 6: Accessing Anjeti control panel.

    Anjeti will be available on HTTP port 8000 by default. Open your favourite browser and navigate to http://yourdomain.com:8000 or http://server-ip:8000 and enter default username “admin” or “root” and password is “admin”.

    Change the password immediately to something secure.

    NRPE installation Ubuntu

    NRPE installation installation Ubuntu

    Tested: Ubuntu 14.04 64 bit

    #Install necessary packages
    apt-get install gettext autoconf gcc libc6 libmcrypt-dev make libssl-dev wget automake libtool bc gawk dc build-essential snmp libnet-snmp-perl

    #Add icinga user and group
    groupadd -g 9000 icinga
    useradd -u 9000 -g icinga -d /usr/local/nagios -c "Nagios NRPE" icinga

    # Install latest NRPE

    cd /usr/local/src/
    wget --no-check-certificate -O nrpe.tar.gz https://github.com/NagiosEnterprises/nrpe/archive/nrpe-3.2.0.tar.gz
    tar xvf nrpe.tar.gz
    cd nrpe-nrpe-3.2.0
    ./tools/setup
    ./configure --enable-command-args --with-ssl-lib=/usr/lib/x86_64-linux-gnu/ --with-nrpe-user=icinga --with-nrpe-group=icinga --with-nagios-user=icinga --with-nagios-group=icinga #Ubuntu x86_x64
    #For Ubuntu i386
    #./configure --enable-command-args --with-ssl-lib=/usr/lib/i386-linux-gnu/ --with-nrpe-user=icinga --with-nrpe-group=icinga --with-nagios-user=icinga --with-nagios-group=icinga
    make all
    make install
    make install-config

    #Update Services File
    echo “Adding nrpe to running services”
    echo “nrpe 5666/tcp # Nagios NRPE” >>/etc/service
    s

    #Install Service / Daemon
    make install-init
    #Ubuntu 13.x / 14.x

    #systemctl enable nrpe.service #Ubuntu 15.x / 16.x / 17.x

    #Open the incoming TCP port 5666 on your firewall. You will have to do this using firewall software, like firewall ufw.

    #Update Configuration File
    The file nrpe.cfg is where the following settings will be defined. It is located:

    /usr/local/nagios/etc/nrpe.cfg

    allowed_hosts=

    At this point NRPE will only listen to requests from itself (127.0.0.1). If you wanted your nagios server to be able to connect, add it's IP address after a comma (in this example it's 10.25.5.2):

    allowed_hosts=127.0.0.1,10.25.5.2

    The following commands make the configuration changes described above.

    sudo sh -c "sed -i '/^allowed_hosts=/s/$/,10.25.5.2/' /usr/local/nagios/etc/nrpe.cfg"
    sudo sh -c "sed -i 's/^dont_blame_nrpe=.*/dont_blame_nrpe=1/g' /usr/local/nagios/etc/nrpe.cfg"

    #Start Service / Daemon

    Different Linux distributions have different methods of starting NRPE.

    Ubuntu 13.x / 14.x

    sudo start nrpe

    Ubuntu 15.x / 16.x / 17.x

    sudo systemctl start nrpe.service

    Test NRPE

    Now check that NRPE is listening and responding to requests.

    /usr/local/nagios/libexec/check_nrpe -H 127.0.0.1

    You should see the output similar to the following:
    NRPE v3.2.0

    If you get the NRPE version number (as shown above), NRPE is installed and configured correctly.

    You can also test from your Nagios host by executing the same command above, but instead of 127.0.0.1 you will need to replace that with the IP Address / DNS name of the machine with NRPE running.

    Service / Daemon Commands

    Different Linux distributions have different methods of starting / stopping / restarting / status NRPE.

    Ubuntu 13.x / 14.x

    sudo start nrpe
    sudo stop nrpe
    sudo restart nrpe
    sudo status nrpe

    Ubuntu 15.x / 16.x / 17.x

    sudo systemctl start nrpe.service
    sudo systemctl stop nrpe.service
    sudo systemctl restart nrpe.service
    sudo systemctl status nrpe.service

    Installing The Nagios Plugins

    NRPE needs plugins to monitor different parameters. T

    #Install Latest Nagios plugins

    cd /usr/local/src/
    wget --no-check-certificate -O nagios-plugins.tar.gz https://github.com/nagios-plugins/nagios-plugins/archive/release-2.2.1.tar.gz
    tar zxf nagios-plugins.tar.gz
    cd nagios-plugins-release-2.2.1/
    ./tools/setup
    ./configure --enable-perl-modules
    make
    make install

    #Test NRPE + Plugins

    Using the check_load command to test NRPE:
    /usr/local/nagios/libexec/check_nrpe -H 127.0.0.1 -c check_load

    You should see the output similar to the following:
    OK - load average: 0.01, 0.13, 0.12|load1=0.010;15.000;30.000;0; load5=0.130;10.000;25.000;0; load15=0.120;5.000;20.000;0;

    You can also test from your Nagios host by executing the same command above, but instead of 127.0.0.1 you will need to replace that with the IP Address / DNS name of the machine with NRPE running.

    Run Postfix on multiple ports

    Adding additional SMTP listenerports

    By default postfix run on port 25 and 587(TLS). However some ISPs block port 25. In that case you can configure the postfix mail server to listen on addional ports too, for example port 26 or some random 5125.

    This configuration is done in the master.cf configuration file. Edit it in your editor of choice.

    This file is in the following format:

    # ==========================================================================
    # service type private unpriv chroot wakeup maxproc command + args
    # (yes) (yes) (yes) (never) (100)
    # ==========================================================================

    The first column is the port number that you want to listen on. The default SMTP port 25 line will read as follows:

    smtp inet n - - - - smtpd

    To add an additional listener port of 5125, insert the the following after the above:

    5125 inet n - n - - smtpd

    Save the file and restart postfix service

    service postfix restart

    Now you can use port 25, 587 and 5125 to connect to your mail server.

    CSR generation for UCC certificates

    Unified Communications (UC) Certificates (also called SAN Certificates) use Subject Alternative Names o secure multiple sites (e.g. fully qualified domain names) with one certificate. Four SANs are included in the base price of the UC Certificate, but you can purchase additional names at any time during the lifetime of the certificate.

    With a UC Certificate, you can secure:

    www.linuxwebhostingsupport.in
    www.example2.com
    www.example3.net
    mail.example.net
    dev.example2.com

    The CSR generation process is little different for creating an UCC certificates. We will have to create a Openssl based configuration file and then create private key and CSR from it.

    Step 1: Create a custom OpenSSL Conf file.

    The following is an example conf file that can be used for creation of a SAN/UCC cert. Save it as multissl.conf

    ———–
    [ req ]
    default_bits = 2048
    default_keyfile = privkey.pem
    distinguished_name = req_distinguished_name
    req_extensions = req_ext # The extentions to add to the self signed cert

    [ req_distinguished_name ]
    countryName = Country Name (2 letter code)
    countryName_default = US
    stateOrProvinceName = State or Province Name (full name)
    stateOrProvinceName_default = Iowa
    localityName = Locality Name (eg, city)
    localityName_default = Iowa City
    organizationName = Organization Name (eg, company)
    organizationName_default = The University of Iowa
    organizationalUnitName = Organizational Unit Name (eg, section)
    organizationalUnitName_default = Domain Control Validated
    commonName = Common Name (eg, YOUR SSL domain name)
    commonName_max = 64

    [ req_ext ]
    subjectAltName = @alt_names

    [alt_names]
    DNS.1 = www.linuxwebhostingsupport.in
    DNS.2 = www.example1.com
    DNS.3 = example2.com
    ———–

    Notes:

    The alt_names section (DNS.1, DNS.2, ….) are the list of all other domain names you wish to secure with this cert. Additional can be added such as DNS.4, etc.
    The following examples assume that you name the above config file file multissl.conf (if it is named differently you must adjust the filename in the below examples accordingly.
    Step 2: Generate the Private key and CSR with OpenSSL

    Execute the following OpenSSL command

    $ openssl req -nodes -newkey rsa:2048 -keyout serverfqdn.key -out multidomain.csr -config multissl.conf

    * Replace “serverfqdn” with the fully qualified domain name of the server (ie: sample.server.uiowa.edu). Note: it may also be helpful to add a year to the filename.

    You will then see output and be prompted for configuration as seen in the following example. Enter your details accordingly.

    ——————————————
    $ openssl req -nodes -newkey rsa:2048 -keyout serverfqdn.key -out multidomain.csr -config multissl.conf
    Generating a 2048 bit RSA private key
    ………………………………….+++
    …………………………………………………………+++
    writing new private key to ‘serverfqdn.key’
    —–
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter ‘.’, the field will be left blank.
    —–
    Country Name (2 letter code) [US]:US
    State or Province Name (full name) [Iowa]:Iowa
    Locality Name (eg, city) [Iowa City]:Iowa City
    Organization Name (eg, company) [The University of Iowa]:My Company name
    Organizational Unit Name (eg, section) [Domain Control Validated]:IT SUPPORT
    Common Name (eg, YOUR SSL domain name) []:www.linuxwebhostingsupport.in
    ——————————————

    Note: Replace www.linuxwebhostingsupport.in with the “primary” domain name you want secured with this certificate (likely, but not necessarily the hostname of the machine).

    At this point you should have the new key file, and CSR. Save the key file in a secure place, it will be needed to apply the new certificate. The CSR can now be submitted to request the SSL Cert.

    Page 1 of 2

    Powered by WordPress & Theme by Anders Norén