Setting Up OpenERP (Odoo) 9 with Nginx on RHEL/CentOS and Debian/Ubuntu

Odoo, formerly known as OpenERP, is an Open Source Enterprise Resource Planning ERP web based business software written in Python which comes with a suite of web apps designed for every business, such as Website Builders, eCommerce modules, Billing and Accounting, Human Resources, Point of Sale, Customer Relationship Management, Inventory module, Live Chat and many other apps and features.

This tutorial will guide you on you how to install the latest stable version of Odoo (version 9) on a RHEL/CentOS/Fedora or Debian/Ubuntu based systems with Nginx server to act as a reverse proxy in frontend in order to access the web interface faster, securely and from standard web browsing ports, without the need to burden the users to use browser redirect ports.

Step 1: Install and Secure PostgreSQL Database

1. Before you start proceeding with Odoo installation first assure that your system ships with packages provided by Epel repositories in order to install the backend PostgreSQL database.

Also make sure the server is up-to-date with the latest security packages and patches by issuing the below commands:

----------- On RedHat/CentOS based systems ----------- 
# yum update
# yum install -y epel-release

----------- On Debian/Ubuntu based systems ----------- 
# apt-get update && sudo apt-get upgrade # On Debian 

2. Next, go ahead and install PostgreSQL database server, which is the default database used by Odoo to store information.

----------- On RedHat/CentOS based systems -----------
# yum install postgresql-server

----------- On Debian/Ubuntu based systems -----------
# apt-get install postgresql postgresql-client

Initialize PostgreSQL database.

# postgresql-setup initdb	

Now finally start the PostgreSQL database by issuing the below command:

----------- On SystemD systems -----------
# systemctl start postgresql

----------- On SysVinit systems -----------
# service postgresql start

As an additional step to secure PostgreSQL default user, which has a blank password, issue the below command with root privileges in order to change the password:

sudo -u postgres psql
postgres=# \password postgres

Step 2: Install Odoo 9 – OpenERP

3. In order to install Odoo 9 from official repository, first create new yum repository file for Odoo with the following content:

On CentOS/RHEL Systems

# vi /etc/yum.repos.d/odoo.repo

Add the following excerpt to file odoo.repo.

[odoo-nightly]
name=Odoo Nightly repository
baseurl=http://nightly.odoo.com/9.0/nightly/rpm/
enabled=1
gpgcheck=1
gpgkey=https://nightly.odoo.com/odoo.key

On Debian/Ubuntu Systems

On Debian/Ubuntu issue the following command to add the Odoo repositories:

# wget -O - https://nightly.odoo.com/odoo.key | apt-key add -
# echo "deb http://nightly.odoo.com/9.0/nightly/deb/ ./" >> /etc/apt/sources.list

4. Next install Odoo 9 software from binaries.

----------- On RedHat/CentOS based systems -----------
# yum install odoo

----------- On Debian/Ubuntu based systems -----------
# apt-get update && sudo apt-get install odoo

Next, start it and check daemon status by issuing the below commands:

----------- On SystemD systems -----------
# systemctl start odoo
# systemctl status odoo

----------- On SysVinit systems -----------
# service odoo start
# service odoo status

As an additional step you can verify Odoo service listening port by running the ss or netstat command:

# ss -tulpn
OR
# netstat -tulpn

By default, Odoo listens for network connections on port 8069/TCP.

Step 3: Configure Odoo from Web Interface

5. In order to configure Odoo further fire-up a browser and access Odoo web interface at the following URI:

http://host-or-IP-address:8069/

6. Next you will be prompted to create a new database for Odoo and set a strong password for admin account.

Create Odoo Database

Create Odoo Database

7. Once the database has been created you will be redirected to the administration web panel where you can further install applications and configure your ERP. For the moment leave the application as default and log out.

Odoo Administrative Web Panel

Odoo Administrative Web Panel

8. Once returned at the login screen, hit on Manage Databases link and Set a master password in order to secure Odoo database manager.

Odoo Manage Databases

Odoo Manage Databases

Set Odoo Database Manager Password

Set Odoo Database Manager Password

Set New Odoo Manager Password

Set New Odoo Manager Password

9. Once you have secured Odoo database manager you can login on your application and start to configure it further with your required apps and settings.

Install Configure Odoo Applications

Install Configure Odoo Applications

Step 4: Access Odoo from Nginx Frontend

You can configure the system so that users can access Odoo web panel via Nginx reverse proxy. This can facilitate the users to navigate Odoo web interface faster, due to some Nginx frontend caching, on standard HTTP ports without the need to manually enter the http port 8069 on their browsers.

In order to configure this setting first you need to install and configure Nginx on your system by issuing the following steps.

10. First install Nginx web server with the following command:

----------- On RedHat/CentOS based systems -----------
# yum install nginx

----------- On Debian/Ubuntu based systems -----------
# apt-get install nginx

11. Next, open Nginx main configuration file with a text editor and insert the following block after the line which specifies Nginx document root location.

----------- On RedHat/CentOS based systems -----------
# vi /etc/nginx/nginx.conf 

----------- On Debian/Ubuntu based systems -----------
# nano /etc/nginx/sites-enabled/default

Add the following configuration excerpt to nginx.conf file:

 location / {
        proxy_pass http://127.0.0.1:8069;
        proxy_redirect off;
        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;

Also, comment Nginx location statement by placing a # in front of the following lines. Use the below screenshot as a guide.

#location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
        #       try_files $uri $uri/ =404;
        #}

Configure Nginx for Odoo Reverse Proxy

Configure Nginx for Odoo Reverse Proxy

12. After you’ve made all the above changes, restart Nginx daemon but not before you run getenforcecommand to check if Selinux in enabled on your machine.

On CentOS/RHEL Systems

In case the policy is set to Enforced disable it by issuing the below commands:

# setenforce 0
# getenforce

To completely disable Selinux, open /etc/selinux/config file with a text editor and set the line SELINUX to disabled.

Disable SELinux in CentOS and RHEL

Disable SELinux in CentOS and RHEL

If you don’t want to completely disable Seliux policy and just want to relax the rules in order to grant Nginx proxy with permissive access to network socket run the following command:

# setsebool httpd_can_network_connect on -P
# getsebool -a | grep httpd 

Then, restart Nginx daemon to reflect the changes made above:

# systemctl restart nginx
OR
# service nginx restart

13. This next step is a security optional feature and implies the change of the network socket that Odooapplication is listening, changing the binding address from all interfaces (or address) to localhost only.

This change must be done only in conjunction with Nginx reverse proxy due to the fact that binding the application on localhost only implies that Odoo will not be accessible from users inside the LAN or other networks.

In order to active this change, open /etc/odoo/openerp-server.conf file and edit xmlrpc_interfaceline to bind on localhost only as suggested on the below screenshot.

xmlrpc_interface = 127.0.0.1

Configure Odoo Interface

Configure Odoo Interface

In order to reflect changes restart Odoo service by running the below command:

# systemctl restart odoo.service
OR
# service odoo restart

14. In case your machine has a network defense line provided by the firewall, issue the following commands in order to open firewall ports to outside world for Nginx proxy:

----------- On FirewallD based systems -----------
# firewall-cmd --add-service=http --permanent
# firewall-cmd --reload
----------- On IPTables based systems -----------
# iptables -A INPUT -p tcp -m tcp --sport 80 -j ACCEPT
# iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
# /etc/init.d/iptables save
----------- On UFW Firewall systems -----------
# ufw allow http

15. That’s it! Now you can successfully access your ERP Odoo application by visiting your server IP Address or domain name.

http://192.168.1.40
http://domain.tld

Odoo Web Interface

Odoo Web Interface

16. In order to automatically run the services after a system reboot issue the following command to enable all the daemons system-wide with one-shot.

------------ On SystemD Systems ------------  
# systemctl enable postgresql.service 
# systemctl enable odoo.service
# systemctl enable nginx.service
------------ On SysVinit Systems ------------ 

# chkconfig postgresql on
# chkconfig odoo on
# chkconfig nginx on

NOTE: For PDF reports, you must manually download and install wkhtmltopdf binary packages for your own distribution by visiting the following link Install wkhtmltopdf to Convert HTML Page to PDF.

Source

5 Tips to Boost the Performance of Your Apache Web Server

According to a recent report by Netcraft (a well-known Internet company that provides among other services web browser usage statistics), Apache continues to be the most widely used web server among sites and Internet-facing computers.

Improve Apache Web Server Performance

5 Tips to Boost Your Apache Web Server Performance

Additionally, Apache keeps experiencing the largest growth among the top web servers, followed by Nginx and IIS. Thus, if you are a system administrator in charge of managing Apache installations, you need to know how to make sure your web server performs at the best of its capacity according to your (or you client’s) needs.

In this article we will discuss a few tips that will help you ensure that Apache will run smoothly and be able to handle the number of requests you are expecting from remote clients.

However, please keep in mind that Apache was not designed with the objective of setting benchmark records – but, even so, it is still capable of providing high performance in almost any usage case you can possibly think of.

​TIP #1: Always keep Apache updated to its latest version

It goes without saying that having the latest version of Apache installed is probably one of the first things you need to consider. As of November 19, 2015, the latest version of Apache available in the CentOS 7 repositories is 2.4.6, whereas in Debian’s is 2.4.10.

However, there may be a recent improvement or a bug fix that has been added to a newly-released stable version, which is then made available to download and install from source. Compilation and installation instructions are also provided here – just remember that if you choose this update method, you may want to back up your current configuration files / sites / virtual hosts as a precaution.

In any event, you can check your currently installed version as follows:

# httpd -v               [On RedHat/CentOS based systems]
# apache2 –v             [On Debian/Ubuntu based systems] 

Check Apache Version

Check Apache Version

As a rule of thumb, stick with the update method provided by the package manager of your chosen distribution (yum update httpd or aptitude safe-upgrade apache2, for CentOS or Debian, respectively) unless there is no other way. You can read the latest release notes in the Apache Documentation section in the Apache HTTP server Project website.

TIP #2: If you are using a Kernel older than 2.4, consider upgrading now

Why? Kernel versions 2.4 and above have the sendfile kernel system call enabled by default. That, in turn, facilitates high performance network file transfers (which are desired in the context of web server-client communications) and enables Apache to deliver static content faster and with lower CPU utilization by performing simultaneous read and send operations.

You can view your currently installed kernel with:

# uname -r

and compare it to the latest stable kernel in www.kernel.org (4.3 at the time of this writing).

Check Linux Kernel Version

Check Linux Kernel Version

Although it is a process not intended for beginners, upgrading your kernel is an interesting exercise to learn more about the internals of Linux.

​TIP #3: Choose the Multi-Processing Module (MPM) that works best for your case

In practice, MPMs extend the modular functionality of Apache by allowing you to decide how to configure the web server to bind to network ports on the machine, accept requests from clients, and use children processes (and threads, alternatively) to handle such requests.

Beginning with version 2.4, Apache offers three different MPMs to choose from, depending on your needs:

    1. The prefork MPM uses multiple child processes without threading. Each process handles one connection at a time without creating separate threads for each. Without going into too much detail, we can say that you will want to use this MPM only when debugging an application that uses, or if your application needs to deal with, non-thread-safe modules like mod_php.
    2. The worker MPM uses several threads per child processes, where each thread handles one connection at a time. This is a good choice for high-traffic servers as it allows more concurrent connections to be handled with less RAM than in the previous case.
  1. Finally, the event MPM is the default MPM in most Apache installations for versions 2.4 and above. It is similar to the worker MPM in that it also creates multiple threads per child process but with an advantage: it causes KeepAlive or idle connections (while they remain in that state) to be handled by a single thread, thus freeing up memory that can be allocated to other threads. This MPM is not suitable for use with non-thread-safe modules like mod_php, for which a replacement such a PHP-FPM must be used instead.

To check the MPM used by your Apache installation, you can do:

# httpd -V

The image below show that this particular web server is using the prefork MPM.

Check Apache MPM

Check Apache MPM

To change this, you will need to edit:

# /etc/httpd/conf.modules.d/00-mpm.conf          [On RedHat/CentOS based systems]
# /etc/apache2/mods-available/<mpm>.load   [On Debian/Ubuntu based systems]

Where <mpm> can be mpm_eventmpm_worker, or mpm_prefork.

and uncomment the line that loads the desired module like so:

LoadModule mpm_event_module modules/mod_mpm_event.so

Note: To make the event MPM work in Debian, you may have to install the libapache2-mod-fastcgi package from the non-free repositories.

Additionally, for CentOS you will need php-fpm (along with fcgi and mod_fcgid) whereas in Debian it’s called php5-fpm (along with apache2-mpm-event).

Last, but not least, restart the web server and the newly installed php-fpm (or php5-fpm) service:

On RedHat/CentOS

# systemctl restart httpd php-fpm && systemctl enable httpd php-fpm

On Debian/Ubuntu

# systemctl restart apache2 php5-fpm && systemctl enable apache2 php5-fpm

Although you can set Apache to use a specific MPM, that configuration can be overridden on a per-virtual hostbasis in the same fashion as indicated earlier.

Just drop the corresponding tags into the configuration file for each virtual host and you’re ready to go – but make sure you’re using one and only one MPM per vhost.

Finally, please note that regardless of your chosen distribution, php-fpm relies on the implementation of FastCGI, which is the reason why I recommended the additional package installations earlier.

For more details and examples on php-fpm and how it can along with the event MPM increase the performance of Apache, you should refer to the official documentation.

This is what I see after changing the default MPM from prefork to event in the same box shown in the previous image:

Choose Apache MPM Module

Choose Apache MPM Module

In CentOS 7, you will need to make sure that the http and https services are enabled through the firewall, and that the network interface(s) are properly added to the default zone.

For example:

# firewall-cmd --zone=internal --add-interface=tun6to4 
# firewall-cmd --zone=internal --add-interface=tun6to4 --permanent 
# firewall-cmd --set-default-zone=internal 
# firewall-cmd --add-service=http 
# firewall-cmd --add-service=https 
# firewall-cmd --add-service=http --permanent 
# firewall-cmd --add-service=https --permanent 
# firewall-cmd --reload

The reason why I’m bringing this up is because I recently experienced an issue where the default firewalld configuration settings in a cloud VPS prevented php-fpm and Apache from processing php files.

As a basic test (I am sure you can think of more complicated or stressful ones), I will create a php file that checkes the existence of another file named test.php in the same directory of two CentOS 7 servers with the same hardware characteristics and load but with different MPM. One of them will use event and the other one will use prefork:

Compare Apache Event and Prefork Module

Compare Apache Event and Prefork Module

This is the php code that I’ve saved into a file named checkiffileexists.php:

<?php
$filename = 'test.php';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

Then we will run the Apache benchmark tool (ab) with 200 simultaneous requests until 2000 requests are completed:

# ab -k -c 100 -n 2000 localhost/checkiffileexists.php

Let’s run the test and compare the results. Pay attention to the performance statistics:

Apache Performance Load Testing

Apache Performance Load Testing

As you can see, the performance of the server with event is highly superior to its prefork counterpart in every aspect of this test.

TIP #4: Allocate RAM wisely for Apache

Perhaps the most critical hardware item to be taken into account is the amount of RAM allocated for each Apache process. While you cannot control this directly, you can restrict the number of child processes through the MaxRequestWorkers directive (formerly known as MaxClients in Apache 2.2), which will put limits on the RAM usage by Apache. Again, you can set this value on a per host or per virtual host basis.

To do this, you should take note of the average amount of RAM used by Apache, then multiply it by the number of MaxRequestWorkers, and that is the amount of memory that will be allocated for Apache processes. One thing you never want your web server to do is to begin using swap, as that will significantly decrease its performance. Thus, you should always keep the usage of RAM by Apache within the limits that you can afford and never rely on swap for it.

For example, the following block will restrict the number of simultaneous clients to 30. If more clients hit the host, they may experience a delay or a momentary failure that can be easily solved by refreshing the browser. While this may be considered undesirable, it is healthier for the server and in the long run, best for your site as well.

You can place this block inside /etc/httpd/conf/httpd.conf or /etc/apache2/apache2.conf, depending on whether you are using CentOS or Debian.

Please note that the same principle applies to all MPMs – I am using event here to continue with the concept outlined in the previous tip:

<IfModule mpm_event_module>
    StartServers 3
    MinSpareThreads          25
    MaxSpareThreads          75
    ThreadLimit                      64
    ThreadsPerChild          25
    MaxRequestWorkers    30
    MaxConnectionsPerChild    1000
</IfModule>

In any event, it is highly recommended that you refer to the Apache 2.4 docs to see which directives are allowed for your chosen MPM.

​TIP #5: Know your applications

As a rule of thumb, you should not load any Apache modules that are not strictly needed for your application to work. This will require at least an overall knowledge of the applications running on your server, specially if you are a system administrator and there’s another team in charge of development.

You can list the currently loaded modules with:

# httpd -M          [On RedHat/CentOS based systems]
# apache2ctl -M     [On Debian/Ubuntu based systems]

To unload / disable modules in CentOS, you will need to comment out the line that begins with LoadModule(either in the main configuration file or in an auxiliary one inside /etc/httpd/conf.modules.d.

On the other hand, Debian provides a tool called a2dismod to disable modules and is used as follows:

# a2dismod module_name

To enable it back:

# a2enmod module_name

In either case, remember to restart Apache for the changes to take effect.

​ Summary

In this article we have reviewed 5 tips that will help you tune the Apache web server and increase its performance. In addition, you should remember that optimization and performance without security is pointless, so you may want to refer to the install mod_pagespeed to improve webserver performance and Apache hardening tips article in Tecmint.com as well.

Since we cannot adequately cover all the aspects of this topic in this article, perhaps you will think of other ideas that you would like to share with the rest of the community. If so, feel free to let us know using the comment form below.

Source

How to Password Protect Web Directories in Apache Using .htaccess File

When you manage online projects, you often need to limit access to that project in order to protect it against the outside world. There are might be different reasons for that – for example you want to prevent search engine crawlers from accessing your site while it is still in development phase.

Password Protect Apache Web Directories

Password Protect Apache Web Directories

In this tutorial, I am going to show you how to password protected different web sites directories in Apache web server. There are many ways you can achieve this, but we will review two of them which are most commonly used.

The first method configures password protection directly in Apache’s configuration file, while the second one uses .htaccess file.

Requirements

In order to setup password protection for your web directories, you will need to have:

  • A working Apache web server
  • The AllowOverride AuthConfig directive must be enabled in Apache configuration file.

Setup Apache Password Protected Directory

1. For this tutorial, we will be protecting the main web root directory /var/www/html.  To protect that directory, open your Apache’s configuration:

---------------- On RedHat/CentOS based systems ----------------
# vi /etc/httpd/conf/httpd.conf

---------------- On Debian/Ubuntu based systems ----------------
# nano /etc/apache2/sites-available/000-default.conf

2. Find the Apache Document directory root for /var/www/html and add the following things as suggested:

On Apache 2.2 Version

<Directory /var/www/html> 
Options Indexes Includes FollowSymLinks MultiViews 
AllowOverride All
Order allow,deny
Allow from all 
</Directory>

On Apache 2.4 Version

<Directory /var/www/html> 
Options Indexes Includes FollowSymLinks MultiViews 
AllowOverride All 
Require all granted 
</Directory>

Apache 2.4: Enable AllowOverride All

Apache 2.4: Enable AllowOverride All

3. Save the file and restart Apache by using the following command:

--------------- On Systemd -------------------
# systemctl restart httpd         [On RedHat based systems]
# systemctl restart apache2       [On Debian based systems]


--------------- On SysV init -----------------
# service httpd restart           [On RedHat based systems]
# service apache2 restart         [On Debian based systems]

4. Now we will use the htpasswd command to generate username and password for our protected directory. This command is used to manage user files for basic authentication.

The general syntax of the command is:

# htpasswd -c filename username

The -c option specifies the file that will keep the encrypted password and username specifies the user for the authentication.

5. Our password file needs to be located out of the Apache’s web accessible directory so that it is well protected. For that purpose, we will create new directory:

# mkdir /home/tecmint

6. After that we will generate our username and password that will be stored in that directory:

# htpasswd -c /home/tecmint/webpass tecmint

Once you execute this command you will have to enter a password for our new user "tecmint" twice:

Create Apache User Password

Create Apache User Password

After that we will need to make sure that Apache is able to read the “webpass” file. For that purpose, you will need to change the ownership of that file with the following command:

---------------- On RedHat/CentOS based systems ----------------
# chown apache: /home/tecmint/webpass
# chmod 640 /home/tecmint/webpass
---------------- On Debian/Ubuntu based systems ----------------
# chown www-data /home/tecmint/webpass
# chmod 640 /home/tecmint/webpass

7. At this point our new user and password are ready. Now we need to tell Apache to request password when accessing our targeted directory. For that purpose, create file called .htaccess in /var/www/html:

# vi /var/www/html/.htaccess

Add the following code in it:

AuthType Basic
AuthName "Restricted Access"
AuthUserFile /home/tecmint/webpass
Require user tecmint

Create Apache Restricted Access

Create Apache Restricted Access

8. Now save the file and put your setup to the test. Open your browser and enter your IP address or domain name in the web browser, for example:

http://ip-address

You should be prompted for username and password:

Apache Password Protected Directory Authentication

Apache Password Protected Directory Authentication

Enter the username and password that you set to proceed to your page.

Additional Notes

If you are using shared hosting, you will most probably not have access to the Apache configuration file. However most hosting companies have enabled the “AllowOverride All” option by default. This means that you will only need to generate the username and password and then select directory that you wish to protect. This significantly eases your task.

Conclusion

I hope that you found this tutorial useful and help you achieve your goal. If you have any questions or comments, please do not hesitate to post them in the section below.

Source

Limit CPU Usage of a Process in Linux with CPULimit Tool

In an earlier post, we’ve explained CPUTool for limiting and controlling CPU utilization of any process in Linux. It allows a system administrator to interrupt execution of a process (or process group) if the CPU/system load goes beyond a defined threshold. Here, we will learn how to use a similar tool called cpulimit.

Cpulimit is used to restrict the CPU usage of a process in the same way as CPUTool, however, it offers more usage options compared to its counterpart. One important difference is that cpulimit doesn’t manage system load unlike cputool.

Suggested Read: 9 Useful Commands to Get CPU Information on Linux

Install CPULimit to Limit CPU Usage Of a Process in Linux

CPULimit is available to install from default software repositories of Debian/Ubuntu and its derivatives using a package management tool.

$ sudo apt install cpulimit

In RHEL/CentOS and Fedora, you need to first enable EPEL repository and then install cpulimit as shown.

# yum install epel-release
# yum install cpulimit

Limiting Process CPU Usage With CUPLimit

In this sub section, we’ll explain how cpulimit works. First, let’s run a command (same dd command we looked at while covering cputool) which should result into a high CPU percentage, in the background (note that the process PID is printed out after running the command).

$ dd if=/dev/zero of=/dev/null &

[1] 17918

Next, we can use the top or glances tools which output the actual frequently updated state of a running Linux system, to watch the CPU usage of the command above.

$ top

Monitor CPU Usage in Linux

Monitor CPU Usage in Linux

Looking at the output above, we can see that the dd process is utilizing the highest percentage of CPU time 100.0%.

But we can limit this using cputlimit as follows. The --pid or -p option is used to specify the PID and --limit or -l is used to set a usage percentage for a process.

The command below will limit the dd command (PID 17918) to 50% use of one CPU core.

$ sudo cpulimit --pid 17918 --limit 50  

Process 17918 detected

Once we run cpulimit, we can view the current CPU usage for the dd command with top or glances. From the output, the value ranges from (51.5%-55.0% or slightly beyond).

Limit CPU Usage of Process in Linux

Limit CPU Usage of Process in Linux

We can throttle its CPU usage for a second time as follows, this time lowering the percentage further as follows:

$ sudo cpulimit --pid 17918 --limit 20 

Process 17918 detected

As we did before, we can run top or glances to view the new CPU usage for the process, which will range from 20%-25.0% or slightly beyond this.

$ top

Throttle CPU Usage in Linux

Throttle CPU Usage in Linux

Note: The shell becomes un-interactive – doesn’t expect any user input when cpulimit is running. To kill it (which should stop the CPU usage limitation operation), press [Ctrl + C].

To run cpulimit as a background process, use the --background or -b switch, freeing up the terminal.

$ sudo cpulimit --pid 17918 --limit 20 --background

To specify the number of CPU cores present on the system, use the --cpu or -c flag (this is normally detected automatically).

$ sudo cpulimit --pid 17918 --limit 20 --cpu 4

Rather than limit a process’s CPU usage, we can kill it with the --kill or -k option. The default is signal sent to the process is SIGCONT, but to send a different signal, use the --signal or -s flag.

$ sudo cpulimit --pid 17918 --limit 20 --kill 

To exit if there is no suitable target process, or in case it dies, include the -z or --lazy like this.

$ sudo cpulimit --pid 17918 --limit 20 --kill --lazy

For additional information and usage options, view the cpulimit man page.

$ man cpulimit

Do check out the following useful guides for finding CPU info and CPU/system performance monitoring.

  1. Find Top Running Processes by Highest Memory and CPU Usage in Linux
  2. Cpustat – Monitors CPU Utilization by Running Processes in Linux
  3. CoreFreq – A Powerful CPU Monitoring Tool for Linux Systems
  4. Find Top Running Processes by Highest Memory and CPU Usage in Linux
  5. 20 Command Line Tools to Monitor Linux Performance
  6. 13 Linux Performance Monitoring Tools – Part 2

In comparison, after testing CPUTool and CPULimit, we noticed that the former offers a more effective and reliable “process CPU usage limitation” functionality.

This is according to the percentage range of CPU usage observed after running both tools against a given process. Try out both tools and add your thoughts to this article using the feedback form below.

Source

All You Need To Know About Processes in Linux [Comprehensive Guide]

In this article, we will walk through a basic understanding of processes and briefly look at how to manage processes in Linux using certain commands.

process refers to a program in execution; it’s a running instance of a program. It is made up of the program instruction, data read from files, other programs or input from a system user.

Types of Processes

There are fundamentally two types of processes in Linux:

  • Foreground processes (also referred to as interactive processes) – these are initialized and controlled through a terminal session. In other words, there has to be a user connected to the system to start such processes; they haven’t started automatically as part of the system functions/services.
  • Background processes (also referred to as non-interactive/automatic processes) – are processes not connected to a terminal; they don’t expect any user input.

What is Daemons

These are special types of background processes that start at system startup and keep running forever as a service; they don’t die. They are started as system tasks (run as services), spontaneously. However, they can be controlled by a user via the init process.

Linux Process State

Linux Process State

Creation of a Processes in Linux

A new process is normally created when an existing process makes an exact copy of itself in memory. The child process will have the same environment as its parent, but only the process ID number is different.

There are two conventional ways used for creating a new process in Linux:

  • Using The System() Function – this method is relatively simple, however, it’s inefficient and has significantly certain security risks.
  • Using fork() and exec() Function – this technique is a little advanced but offers greater flexibility, speed, together with security.

How Does Linux Identify Processes?

Because Linux is a multi-user system, meaning different users can be running various programs on the system, each running instance of a program must be identified uniquely by the kernel.

And a program is identified by its process ID (PID) as well as it’s parent processes ID (PPID), therefore processes can further be categorized into:

  • Parent processes – these are processes that create other processes during run-time.
  • Child processes – these processes are created by other processes during run-time.

The Init Process

Init process is the mother (parent) of all processes on the system, it’s the first program that is executed when the Linux system boots up; it manages all other processes on the system. It is started by the kernel itself, so in principle it does not have a parent process.

The init process always has process ID of 1. It functions as an adoptive parent for all orphaned processes.

You can use the pidof command to find the ID of a process:

# pidof systemd
# pidof top
# pidof httpd

Find Linux Process ID

Find Linux Process ID

To find the process ID and parent process ID of the current shell, run:

$ echo $$
$ echo $PPID

Find Linux Parent Process ID

Find Linux Parent Process ID

Starting a Process in Linux

Once you run a command or program (for example cloudcmd – CloudCommander), it will start a process in the system. You can start a foreground (interactive) process as follows, it will be connected to the terminal and a user can send input it:

# cloudcmd

Start Linux Interactive Process

Start Linux Interactive Process

Linux Background Jobs

To start a process in the background (non-interactive), use the & symbol, here, the process doesn’t read input from a user until it’s moved to the foreground.

# cloudcmd &
# jobs

Start Linux Process in Background

Start Linux Process in Background

You can also send a process to the background by suspending it using [Ctrl + Z], this will send the SIGSTOP signal to the process, thus stopping its operations; it becomes idle:

# tar -cf backup.tar /backups/*  #press Ctrl+Z
# jobs

To continue running the above-suspended command in the background, use the bg command:

# bg

To send a background process to the foreground, use the fg command together with the job ID like so:

# jobs
# fg %1

Linux Background Process Jobs

Linux Background Process Jobs

You may also like: How to Start Linux Command in Background and Detach Process in Terminal

States of a Process in Linux

During execution, a process changes from one state to another depending on its environment/circumstances. In Linux, a process has the following possible states:

  • Running – here it’s either running (it is the current process in the system) or it’s ready to run (it’s waiting to be assigned to one of the CPUs).
  • Waiting – in this state, a process is waiting for an event to occur or for a system resource. Additionally, the kernel also differentiates between two types of waiting processes; interruptible waiting processes – can be interrupted by signals and uninterruptible waiting processes – are waiting directly on hardware conditions and cannot be interrupted by any event/signal.
  • Stopped – in this state, a process has been stopped, usually by receiving a signal. For instance, a process that is being debugged.
  • Zombie – here, a process is dead, it has been halted but it’s still has an entry in the process table.

How to View Active Processes in Linux

There are several Linux tools for viewing/listing running processes on the system, the two traditional and well known are ps and top commands:

1. ps Command

It displays information about a selection of the active processes on the system as shown below:

# ps 
# ps -e | head 

List Linux Active Processes

List Linux Active Processes

2. top – System Monitoring Tool

top is a powerful tool that offers you a dynamic real-time view of a running system as shown in the screenshot below:

# top 

List Linux Running Processes

List Linux Running Processes

Read this for more top usage examples: 12 TOP Command Examples in Linux

3. glances – System Monitoring Tool

glances is a relatively new system monitoring tool with advanced features:

# glances

Glances - Linux Process Monitoring

Glances – Linux Process Monitoring

For a comprehensive usage guide, read through: Glances – An Advanced Real Time System Monitoring Tool for Linux

There are several other useful Linux system monitoring tools you can use to list active processes, open the link below to read more about them:

  1. 20 Command Line Tools to Monitor Linux Performance
  2. 13 More Useful Linux Monitoring Tools

How to Control Processes in Linux

Linux also has some commands for controlling processes such as kill, pkill, pgrep and killall, below are a few basic examples of how to use them:

$ pgrep -u tecmint top
$ kill 2308
$ pgrep -u tecmint top
$ pgrep -u tecmint glances
$ pkill glances
$ pgrep -u tecmint glances

Control Linux Processes

Control Linux Processes

To learn how to use these commands in-depth, to kill/terminate active processes in Linux, open the links below:

  1. A Guide to Kill, Pkill and Killall Commands to Terminate Linux Processess
  2. How to Find and Kill Running Processes in Linux

Note that you can use them to kill unresponsive applications in Linux when your system freezes.

Sending Signals To Processes

The fundamental way of controlling processes in Linux is by sending signals to them. There are multiple signals that you can send to a process, to view all the signals run:

$ kill -l

List All Linux Signals

List All Linux Signals

To send a signal to a process, use the kill, pkill or pgrep commands we mentioned earlier on. But programs can only respond to signals if they are programmed to recognize those signals.

And most signals are for internal use by the system, or for programmers when they write code. The following are signals which are useful to a system user:

  • SIGHUP 1 – sent to a process when its controlling terminal is closed.
  • SIGINT 2 – sent to a process by its controlling terminal when a user interrupts the process by pressing [Ctrl+C].
  • SIGQUIT 3 – sent to a process if the user sends a quit signal [Ctrl+D].
  • SIGKILL 9 – this signal immediately terminates (kills) a process and the process will not perform any clean-up operations.
  • SIGTERM 15 – this a program termination signal (kill will send this by default).
  • SIGTSTP 20 – sent to a process by its controlling terminal to request it to stop (terminal stop); initiated by the user pressing [Ctrl+Z].

The following are kill commands examples to kill the Firefox application using its PID once it freezes:

$ pidof firefox
$ kill 9 2687
OR
$ kill -KILL 2687
OR
$ kill -SIGKILL 2687  

To kill an application using its name, use pkill or killall like so:

$ pkill firefox
$ killall firefox 

Changing Linux Process Priority

On the Linux system, all active processes have a priority and certain nice value. Processes with higher priority will normally get more CPU time than lower priority processes.

However, a system user with root privileges can influence this with the nice and renice commands.

From the output of the top command, the NI shows the process nice value:

$ top  

List Linux Running Processes

List Linux Running Processes

Use the nice command to set a nice value for a process. Keep in mind that normal users can attribute a nice value from zero to 20 to processes they own.
Only the root user can use negative nice values.

To renice the priority of a process, use the renice command as follows:

$ renice +8  2687
$ renice +8  2103

Check out our some useful articles on how to manage and control Linux processes.

  1. Linux Process Management: Boot, Shutdown, and Everything in Between
  2. Find Top 15 Processes by Memory Usage with ‘top’ in Batch Mode
  3. Find Top Running Processes by Highest Memory and CPU Usage in Linux
  4. How to Find a Process Name Using PID Number in Linux

That’s all for now! Do you have any questions or additional ideas, share them with us via the feedback form below.

Source

9 Useful Commands to Get CPU Information on Linux

In a previous article, we put together a list of 10 useful commands to collect system and hardware information in Linux. In this guide, we will narrow down to the CPU/processor, and show you various ways of extracting detailed information about your machine CPU.

Just to give you an overview, we will query information such as CPU architecture, vendor_id, model, model name, number of CPU cores, speed of each core and lots more.
Essentially, the /proc/cpuinfo contains this all info, every other command/utility gets its output from this file.

With that said, below are 9 commands for getting info about your Linux CPU.

1. Get CPU Info Using cat Command

You can simply view the information of your system CPU by viewing the contents of the /proc/cpuinfo file with the help of cat command as follows:

$ cat /proc/cpuinfo
Linux CPU Information
processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 69
model name	: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
stepping	: 1
microcode	: 0x1c
cpu MHz		: 1700.062
cache size	: 3072 KB
physical id	: 0
siblings	: 4
core id		: 0
cpu cores	: 2
apicid		: 0
initial apicid	: 0
fpu		: yes
fpu_exception	: yes
cpuid level	: 13
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
bugs		:
bogomips	: 4788.92
clflush size	: 64
cache_alignment	: 64
address sizes	: 39 bits physical, 48 bits virtual
power management:
......

To get a little specific, you can employ grep command – a CLI tool for searching plain-text data for lines matching a regular expression. This can help you only output vendor name, model name, number of processors, number of cores etc:

$ cat /proc/cpuinfo | grep 'vendor' | uniq		#view vendor name
$ cat /proc/cpuinfo | grep 'model name' | uniq		#display model name
$ cat /proc/cpuinfo | grep processor | wc -l		#count the number of processing units
$ cat /proc/cpuinfo | grep 'core id'			#show individual cores	

Suggested Read: How to Use ‘cat’ and ‘tac’ Commands with Examples in Linux

2. lscpu Command – Shows CPU Architecture Info

The command lscpu prints CPU architecture information from sysfs and /proc/cpuinfo as shown below:

$ lscpu
Linux CPU Architecture
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 69
Model name:            Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
Stepping:              1
CPU MHz:               1303.687
CPU max MHz:           2700.0000
CPU min MHz:           800.0000
BogoMIPS:              4788.92
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              3072K
NUMA node0 CPU(s):     0-3
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts

3. cpuid Command – Shows x86 CPU

The command cpuid dumps complete information about the CPU(s) collected from the CPUID instruction, and also discover the exact model of x86 CPU(s) from that information.

Make sure to install it before running it.

$ sudo apt install cpuid        #Debian/Ubuntu systems
$ sudo yum install cpuid	#RHEL/CentOS systems 
$ sudo dnf install cpuid	#Fedora 22+ 

Once installed, run cpuid to collect information concerning the x86 CPU.

$ cpuid
Shows x86 CPU Information
CPU 0:
   vendor_id = "GenuineIntel"
   version information (1/eax):
      processor type  = primary processor (0)
      family          = Intel Pentium Pro/II/III/Celeron/Core/Core 2/Atom, AMD Athlon/Duron, Cyrix M2, VIA C3 (6)
      model           = 0x5 (5)
      stepping id     = 0x1 (1)
      extended family = 0x0 (0)
      extended model  = 0x4 (4)
      (simple synth)  = Intel Mobile Core i3-4000Y / Mobile Core i5-4000Y / Mobile Core i7-4000Y / Mobile Pentium 3500U/3600U/3500Y / Mobile Celeron 2900U (Mobile U/Y) (Haswell), 22nm
   miscellaneous (1/ebx):
      process local APIC physical ID = 0x0 (0)
      cpu count                      = 0x10 (16)
      CLFLUSH line size              = 0x8 (8)
      brand index                    = 0x0 (0)
   brand id = 0x00 (0): unknown
   feature information (1/edx):
      x87 FPU on chip                        = true
      virtual-8086 mode enhancement          = true
      debugging extensions                   = true
      page size extensions                   = true
      time stamp counter                     = true
      RDMSR and WRMSR support                = true
      physical address extensions            = true
....

4. dmidecode Command – Shows Linux Hardware Info

dmidecode is a tool for retrieving hardware information of any Linux system. It dumps a computer’s DMI (a.k.a SMBIOS) table contents in a human-readable format for easy retrieval. The SMBIOS specification defines various DMI types, for CPU, use “processor” as follows:

$ sudo dmidecode --type processor
Shows Linux Hardware Information
# dmidecode 3.0
Getting SMBIOS data from sysfs.
SMBIOS 2.7 present.

Handle 0x0004, DMI type 4, 42 bytes
Processor Information
	Socket Designation: U3E1
	Type: Central Processor
	Family: Core i5
	Manufacturer: Intel(R) Corporation
	ID: 51 06 04 00 FF FB EB BF
	Signature: Type 0, Family 6, Model 69, Stepping 1
	Flags:
		FPU (Floating-point unit on-chip)
		VME (Virtual mode extension)
		DE (Debugging extension)
		PSE (Page size extension)
		TSC (Time stamp counter)
		MSR (Model specific registers)
		PAE (Physical address extension)
		MCE (Machine check exception)
		CX8 (CMPXCHG8 instruction supported)
		APIC (On-chip APIC hardware supported)
		SEP (Fast system call)
		MTRR (Memory type range registers)
		PGE (Page global enable)
		MCA (Machine check architecture)
.....

5. Inxi Tool – Shows Linux System Information

Inxi is a powerful command line system information script intended for both console and IRC (Internet Relay Chat). You can use it to instantly retrieve hardware information.

You can install like so:

$ sudo apt install inxi 	#Debian/Ubuntu systems
$ sudo yum install inxi		#RHEL/CentOS systems 
$ sudo dnf install inxi		#Fedora 22+ 

To display complete CPU information, including per CPU clock-speed and CPU max speed (if available), use the -C flag as follows:

$ inxi -C
Print Linux System Information
CPU:       Dual core Intel Core i5-4210U (-HT-MCP-) cache: 3072 KB 
           clock speeds: max: 2700 MHz 1: 1958 MHz 2: 1993 MHz 3: 1775 MHz 4: 1714 MHz

6. lshw Tool – List Hardware Configuration

lshw is a minimal tool for gathering in-depth information on the hardware configuration of a computer. You can use the -C option to select the hardware class, CPU in this case:

$ sudo lshw -C CPU
Print Linux Hardware Configuration
*-cpu                   
       description: CPU
       product: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
       vendor: Intel Corp.
       physical id: 4
       bus info: cpu@0
       version: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
       serial: To Be Filled By O.E.M.
       slot: U3E1
       size: 2626MHz
       capacity: 2700MHz
       width: 64 bits
       clock: 100MHz
       capabilities: x86-64 fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts cpufreq
       configuration: cores=2 enabledcores=2 threads=4

7. hardinfo – Shows Hardware Info in GTK+ Window

hardinfo displays hardware information in a GTK+ window, you can install it as follows:

$ sudo apt install hardinfo 	#Debian/Ubuntu systems
$ sudo yum install hardinfo	#RHEL/CentOS systems 
$ sudo dnf install hardinfo	#Fedora 22+ 

Once you have it installed, type:

$ hardinfo 

Linux System Information

Linux System Information

It also enables you to generate a system hardware info report by clicking on the “Generate Report” button. From the interface below, click on “Generate” to proceed. Note that you can choose the hardware info category to be generated.

Generate System Information Report

Generate System Information Report

Once you have generated the report in html format, you can view it from a web browser as shown below.

Linux System Detailed Information

Linux System Detailed Information

8. hwinfo – Shows Present Hardware Info

hwinfo is used to extract info about hardware present in a Linux system. To display info about your CPU, use the --cpu

$ hwinfo --cpu
Print Present Hardware Information
01: None 00.0: 10103 CPU                                        
  [Created at cpu.460]
  Unique ID: rdCR.j8NaKXDZtZ6
  Hardware Class: cpu
  Arch: X86-64
  Vendor: "GenuineIntel"
  Model: 6.69.1 "Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz"
  Features: fpu,vme,de,pse,tsc,msr,pae,mce,cx8,apic,sep,mtrr,pge,mca,cmov,pat,pse36,clflush,dts,acpi,mmx,fxsr,sse,sse2,ss,ht,tm,pbe,syscall,nx,pdpe1gb,rdtscp,lm,constant_tsc,arch_perfmon,pebs,bts,rep_good,nopl,xtopology,nonstop_tsc,aperfmperf,eagerfpu,pni,pclmulqdq,dtes64,monitor,ds_cpl,vmx,est,tm2,ssse3,sdbg,fma,cx16,xtpr,pdcm,pcid,sse4_1,sse4_2,movbe,popcnt,tsc_deadline_timer,aes,xsave,avx,f16c,rdrand,lahf_lm,abm,epb,tpr_shadow,vnmi,flexpriority,ept,vpid,fsgsbase,tsc_adjust,bmi1,avx2,smep,bmi2,erms,invpcid,xsaveopt,dtherm,ida,arat,pln,pts
  Clock: 2080 MHz
  BogoMips: 4788.92
  Cache: 3072 kb
  Units/Processor: 16
  Config Status: cfg=new, avail=yes, need=no, active=unknown
....

9. nproc – Print Number of Processing Units

nproc command is used to show the number of processing unit present on your computer:

$ nproc

For additional usage info and options, read through the man pages of these commands like this:

$ man commandname

Also check out:

    1. Cpustat – Monitors CPU Utilization by Running Processes in Linux
    2. CoreFreq – A Powerful CPU Monitoring Tool for Linux Systems
    3. Find Top Running Processes by Highest Memory and CPU Usage in Linux
    4. How to Impose High CPU Load and Stress Test on Linux Using ‘Stress-ng’ Tool

That’s it for now! You can share with us additional ways of extracting CPU information in Linux via the feedback form below.

Source

How to Monitor Apache Web Server Load and Page Statistics

As promised in our earlier tutorials of Apache Series, Today we are here with another article on the Apache HTTP web server which can make a System Administrators life much easier to handle load of Apache web server using mod_status module.

What is mod_status?

mod_status is an Apache module which helps to monitor web server load and current httpd connections with an HTML interface which can be accessible via a web browser.

Apache’s mod_status shows a plain HTML page containing the information about current statistics of web server state including.

  1. Total number of incoming requests
  2. Total number of bytes and counts server
  3. CPU usage of Web server
  4. Server Load
  5. Server Uptime
  6. Total Traffic
  7. Total number of idle workers
  8. PIDs with respective client and many more.

The default Apache Project enabled their server statistics page to the general public. To have a demo of busy web site’s status page, visit.

  1. http://www.apache.org/server-status
Testing Environment

We have used following Testing Environment for this article to explore more about mod_status with some practical examples and screen-shots.

  1. Operating System – CentOS 6.5
  2. Application – Apache Web Server
  3. IP Address – 5.175.142.66
  4. DocumentRoot– /var/www/html
  5. Apache Configuration file – /etc/httpd/conf/httpd.conf (for Red Hat)
  6. Default HTTP Port – 80 TCP
  7. Test Configuration Settings – httpd -t

The prerequisites for this tutorial is that you should already aware how to install and configure a Basic Apache Server. If you don’t know how to setup Apache, read the following article that might help you in setting up your own Apache Web Server.

  1. Create Your Own Webserver and Hosting A Website in Linux

How to Enable mod_status in Apache

The default Apache installation comes with mod_status enabled. If not, make sure to enable it in Apache configuration file at.

[root@tecmint ~]# vi /etc/httpd/conf/httpd.conf

Search for the word “mod_status” or keep scrolling down until you find a line containing.

#LoadModule status_module modules/mod_status.so

If you see a ‘#‘ character at the beginning of “LoadModule”, that means mod_status is disabled. Remove the ‘#‘ to enable mod_status.

LoadModule status_module modules/mod_status.so

Configure mod_status

Now again search for the word “Location” or scroll down until you find a section for mod_status which should look like following.

# Allow server status reports generated by mod_status,
# with the URL of http://servername/server-status
# Change the ".example.com" to match your domain to enable.
#
#<Location /server-status>
#    SetHandler server-status
#    Order deny,allow
#    Deny from all
#    Allow from .example.com
#</Location>

In the above section, uncomment the lines for Location directiveSetHandler and the directory restrictionsaccording to your needs. For example, I am keeping it simple with the Order Allowdeny and it’s allowed for all.

<Location /server-status>
   SetHandler server-status
   Order allow,deny
   Deny from all
   Allow from all 
</Location>

Note : The above configuration is the default configuration for default Apache web site (single website). If you’ve created one or more Apache Virtual Hosts, the above configuration will won’t work.

So, basically, you need to define the same configuration for each virtual host for any domains you’ve configured in Apache. For example, the virtual host configuration for mod_status will look like this.

<VirtualHost *:80>
    ServerAdmin tecmint@example.com
    DocumentRoot /var/www/html/example.com
    ServerName example.com
    ErrorLog logs/example.com-error_log
    CustomLog logs/example.com-access_log common
<Location /server-status>
   SetHandler server-status
   Order allow,deny
   Deny from all
   Allow from example.com 
</Location>
</VirtualHost>

Enable ExtendedStatus

The “ExtendedStatus” settings adds more information to the statistics page like, CPU usagerequest per secondtotal traffic, etc. To enable it, edit the the same httpd.conf file and search for the word “Extended” and Uncomment the line and set the status “On” for ExtendedStatus directive.

# ExtendedStatus controls whether Apache will generate "full" status
# information (ExtendedStatus On) or just basic information (ExtendedStatus
# Off) when the "server-status" handler is called. The default is Off.
#
ExtendedStatus On

Restart Apache

Now make sure that you’ve correctly enabled and configured Apache server status page. You can also check for the errors in the httpd.conf configuration using following command.

[root@tecmint ~]# httpd -t

Syntax OK

Once, you get syntax is OK, you can able to restart the httpd service.

[root@tecmint ~]# service httpd restart
Stopping httpd:                                          [  OK  ]
Starting httpd:                                          [  OK  ]

Access mod_status Page

The Apache status page will be accessible via your domain name with “/server-status” at the following URL’s.

http://serveripaddress/server-status

OR

http://serev-hostname/server-status

You will see something similar to the following page with ExtendedStatus enabled.

Apache mod_status

Apache mod_status View

In above Snapshot, you can see that an HTML interface, which shows all information about server uptimeprocess Id with its respective client, the page they are trying to access.

It also shows the meaning and usage of all the abbreviations used to display the status which helps us to understand the situation better.

You can also refresh the page every time seconds (say 5 seconds) to see the updated statistics. To set the automate refresh, please add “?refresh=N” at the end of the URL. Where N can be replaced with the number of seconds which you want your page to get refreshed.

http://serveripaddress/server-status/?refresh=5

Apache mod_status Refresh

Apache mod_status Refresh

Command line Status Page View

You can also view the Apache status page from the command-line interface using the special command-line browsers called links or lynx. You can install them using default package manager utility called yum as shown below.

# yum install links

OR

# yum install lynx

Once, you’ve installed the, you can get the same statistics on your terminal by using following command.

[root@tecmint ~]# links http://serveripaddress/server-status
OR
[root@tecmint ~]# lynx http://serveripaddress/server-status
OR
[root@tecmint ~]#  /etc/init.d/httpd fullstatus
Sample Output
                     Apache Server Status for localhost
   Server Version: Apache/2.2.15 (Unix) DAV/2 PHP/5.3.3
   Server Built: Aug 13 2013 17:29:28

   --------------------------------------------------------------------------
   Current Time: Tuesday, 14-Jan-2014 04:34:13 EST
   Restart Time: Tuesday, 14-Jan-2014 00:33:05 EST
   Parent Server Generation: 0
   Server uptime: 4 hours 1 minute 7 seconds
   Total accesses: 2748 - Total Traffic: 9.6 MB
   CPU Usage: u.9 s1.06 cu0 cs0 - .0135% CPU load
   .19 requests/sec - 695 B/second - 3658 B/request
   1 requests currently being processed, 4 idle workers
 .__.__W...

   Scoreboard Key:
   "_" Waiting for Connection, "S" Starting up, "R" Reading Request,
   "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
   "C" Closing connection, "L" Logging, "G" Gracefully finishing,
   "I" Idle cleanup of worker, "." Open slot with no current process

Srv PID     Acc    M CPU   SS  Req Conn Child Slot     Client        VHost             Request
0-0 -    0/0/428   . 0.30 5572 0   0.0  0.00  1.34 127.0.0.1      5.175.142.66 OPTIONS * HTTP/1.0
                                                                               GET
1-0 5606 0/639/639 _ 0.46 4    0   0.0  2.18  2.18 115.113.134.14 5.175.142.66 /server-status?refresh=5
                                                                               HTTP/1.1
                                                                               GET
2-0 5607 0/603/603 _ 0.43 0    0   0.0  2.09  2.09 115.113.134.14 5.175.142.66 /server-status?refresh=5
                                                                               HTTP/1.1
3-0 -    0/0/337   . 0.23 5573 0   0.0  0.00  1.09 127.0.0.1      5.175.142.66 OPTIONS * HTTP/1.0
                                                                               GET
4-0 5701 0/317/317 _ 0.23 9    0   0.0  1.21  1.21 115.113.134.14 5.175.142.66 /server-status?refresh=5
                                                                               HTTP/1.1
                                                                               GET
5-0 5708 0/212/213 _ 0.15 6    0   0.0  0.85  0.85 115.113.134.14 5.175.142.66 /server-status?refresh=5
                                                                               HTTP/1.1
6-0 5709 0/210/210 W 0.16 0    0   0.0  0.84  0.84 127.0.0.1      5.175.142.66 GET /server-status
                                                                               HTTP/1.1
7-0 -    0/0/1     . 0.00 5574 0   0.0  0.00  0.00 127.0.0.1      5.175.142.66 OPTIONS * HTTP/1.0

   --------------------------------------------------------------------------

    Srv  Child Server number - generation
    PID  OS process ID
    Acc  Number of accesses this connection / this child / this slot
     M   Mode of operation
    CPU  CPU usage, number of seconds
    SS   Seconds since beginning of most recent request
    Req  Milliseconds required to process most recent request
   Conn  Kilobytes transferred this connection
   Child Megabytes transferred this child
   Slot  Total megabytes transferred this slot
   --------------------------------------------------------------------------

    Apache/2.2.15 (CentOS) Server at localhost Port 80

Conclusion

Apache’s mod_status module is a very handy monitoring tool for monitoring performance of a web server’s activity and can able to highlight problems itself. For more information read the status page that can be help you to become a more successful web server administrator.

  1. Apache mod_status Homepage

That’s all for mod_status for now.

Source

Redirect a Website URL from One Server to Different Server in Apache

As promised in our previous two articles (Perform Internal Redirection with mod_rewrite and Show Custom Content Based on Browser), in this post we will explain how to perform a redirection to a resource that has been moved from one server to a different server in Apache using mod_rewrite module.

Suppose you are redesigning your company’s Intranet site. You have decided to store the content and styling (HTML filesJavaScript, and CSS) on one server and the documentation on another – perhaps a more robust one.

Suggested Read: 5 Tips to Boost the Performance of Your Apache Web Server

However, you want this change to be transparent to your users so that they are still able to access the docs at the usual URL.

In the following example, a file named assets.pdf has been moved from /var/www/html in 192.168.0.100(hostname: web) to the same location in 192.168.0.101 (hostname: web2).

In order for users to access this file when they browse to 192.168.0.100/assets.pdf, open Apache’s configuration file on 192.168.0.100 and add the following rewrite rule (or you can also add the following rule to your .htaccess file):

RewriteRule "^(/assets\.pdf$)" "http://192.168.0.101$1"  [R,L]

where $1 is a placeholder for anything that matches the regular expression inside parentheses.

Now save changes, don’t forget to restart Apache, and let’s see what happens when we attempt to access assets.pdf by browsing to 192.168.0.100/assets.pdf:

Suggested Read: 25 Useful ‘.htaccess’ Tricks for Websites

In the above below we can see that the request that was made for assets.pdf on 192.168.0.100 was actually handled by 192.168.0.101.

# tail -n 1 /var/log/apache2/access.log

Check Apache Logs

Check Apache Logs

In this article we have discussed how to perform a redirection to a resource that has been moved to a different server. To wrap up, I’d strongly suggest you take a look at the mod_rewrite guide and Apache redirect guide for future reference.

As always, feel free to use the comment form below if you have any concerns about this article. We look forward to hearing from you!

Source

How to Use Python ‘SimpleHTTPServer’ to Create Webserver or Serve Files Instantly

SimpleHTTPServer is a python module which allows you to instantly create a web server or serve your files in a snap. Main advantage of python’s SimpleHTTPServer is you don’t need to install anything since you have python interpreter installed. You don’t have to worry about python interpreter because almost all Linux distributions, python interpreter come handy by default.

You also can use SimpleHTTPServer as a file sharing method. You just have to enable the module within the location of your shareable files are located. I will show you several demonstrations in this article by using various options.

Step 1: Check for Python Installation

1. Check whether python is installed in your server or not, by issuing below command.

# python –V 

OR

# python  --version

It will show you the version of the python interpreter you’ve got and it will give you an error message if it is not installed.

Check Python Version

Check Python Version

2. You’re lucky if it was there by default. Less work actually. If it was not installed by any chance, install it following below commands.

If you have a SUSE distribution, type yast in the terminal –> Go to Software Management –> Type ‘python’without quotes –> select python interpreter –> press space key and select it –> and then install it.

Simple as that. For that, you need to have SUSE ISO mounted and configured it as a repo by YaST or you can simple install python from the web.

Install Python on Suse

Install Python on Suse

If you’re using different operating systems like RHEL, CentOS, Debian, Ubuntu or other Linux operating systems, you can just install python using yum or apt.

In my case I use SLES 11 SP3 OS and python interpreter comes installed by default in it. Most of the case you won’t have to worry about installing python interpreter on your server.

Step 2: Create a Test Directory and Enable SimpleHTTPServer

3. Create a test directory where you don’t mess with system files. In my case I have a partition called /x01 and I have created a directory called tecmint in there and also I have added some test files for testing.

Create Testing Directory

Create Testing Directory

4. Your prerequisites are ready now. All you have to do is try python’s SimpleHTTPServer module by issuing below command within your test directory (In my case, /x01//).

# python –m SimpleHTTPServer

Enable SimpleHTTPServer

Enable SimpleHTTPServer

5. After enabling SimpleHTTPServer successfully, it will start serving files through port number 8000. You just have to open up a web browser and enter ip_address:port_number (in my case its 192.168.5.67:8000).

SimpleHTTPServer Directory Listing

Directory Listing

6. Now click on link 'tecmint' to browse files and directories of tecmint directory, see the screen below for reference.

Browse Directory Files

Browse Directory Files

7. SimpleHTTPServer serves your files successfully. You can see what has happened at the terminal, after you accessed your server through web browser by having a look at where you executed your command.

Python SimpleHTTPServer Status

Python SimpleHTTPServer Status

Step 3: Changing SimpleHTTPServer Port

8. By default python’s SimpleHTTPServer serves files and directories through port 8000, but you can define a different port number (Here I am using port 9999) as you desire with the python command as shown below.

# python –m SimpleHTTPServer 9999

Change SimpleHTTPServer Port

Change SimpleHTTPServer Port

Directory Listing on Different Port

Directory Listing on Different Port

Step 4: Serve Files from Different Location

9. Now as you tried it, you might like to serve your files in a specific location without actually going to the path.

As an example, if you are in your home directory and you want to server your files in /x01/tecmint/ directory without cd in to /x01/tecmint, Let’s see, how we will do this.

# pushd /x01/tecmint/; python –m SimpleHTTPServer 9999; popd;

Serve Files from Location

Serve Files from Location

Directory Listing on Different Port

Directory Listing on Different Port

Step 5: Serve HTML Files

10. If there’s a index.html file located in your serving location, python interpreter will automatically detect it and serve the html file instead of serving your files.

Let’s have a look at it. In my case I include a simple html script in the file named index.html and locate it in /x01/tecmint/.

<html>
<header><title>TECMINT</title></header>
<body text="blue"><H1>
Hi all. SimpleHTTPServer works fine.
</H1>
<p><a href="https://www.tecmint.com">Visit TECMINT</a></p>
</body>
</html>

Create Index File

Create Index File

Now save it and run SimpleHTTPServer on /x01/tecmint and go to the location from a web browser.

# pushd /x01/tecmint/; python –m SimpleHTTPServer 9999; popd;

Enable Index Page

Enable Index Page

Serving Index Page

Serving Index Page

Very simple and handy. You can serve your files or your own html code in a snap. Best thing is you won’t have to worry about installing anything at all. In a scenario like you want to share a file with someone, you don’t have to copy the file to a shared location or making your directories shareable.

Just run SimpleHTTPServer on it and it is done. There is a few things you have to keep in mind when using this python module. When it serves files it runs on the terminal and prints out what happens in there. When you’re accessing it from the browser or download a file from it, it shows IP address accessed it and file downloaded etc. Very handy isn’t it?

If you want to stop serving, you will have to stop the running module by pressing ctrl+c. So now you know how to use python’s SimpleHTTPServer module as a quick solution to serve your files. Commenting below for the suggestions and new findings would be a great favour to enhance future articles and learn new things.

Reference Links

SimpleHTTPServer Docs

Source

3 Ways to Check Apache Server Status and Uptime in Linux

Apache is a world’s most popular, cross platform HTTP web server that is commonly used in Linux and Unix platforms to deploy and run web applications or websites. Importantly, it’s easy to install and has a simple configuration as well.

Read AlsoHow to Hide Apache Version Number and Other Sensitive Info

In this article, we will show how to check Apache web server uptime on a Linux system using different methods/commands explained below.

1. Systemctl Utility

Systemctl is a utility for controlling the systemd system and service manager; it is used it to start, restart, stop services and beyond. The systemctl status sub-command, as the name states is used to view the status of a service, you can use it for the above purpose like so:

$ sudo systemctl status apache2	  #Debian/Ubuntu 
# systemctl status httpd	  #RHEL/CentOS/Fedora 

Check Apache Status Using Systemctl

Check Apache Status Using Systemctl

2. Apachectl Utilities

Apachectl is a control interface for Apache HTTP server. This method requires the mod_status (which displays info about the server is performing including its uptime) module installed and enabled (which is the default setting).

On Debian/Ubuntu

The server-status component is enabled by default using the file /etc/apache2/mods-enabled/status.conf.

$ sudo vi /etc/apache2/mods-enabled/status.conf

Apache Mod_Status Configuration

Apache Mod_Status Configuration

On RHEL/CentOS

To enable server-status component, create a file below.

# vi /etc/httpd/conf.d/server-status.conf

and add the following configuration.

<Location "/server-status">
    SetHandler server-status
    #Require  host  localhost		#uncomment to only allow requests from localhost 
</Location>

Save the file and close it. Then restart the web server.

# systemctl restart httpd

If you are primarily using a terminal, then you also need a command line web browser such as lynx or links.

$ sudo apt install lynx		#Debian/Ubuntu
# yum install links		#RHEL/CentOS

Then run the command below to check the Apache service uptime:

$ apachectl status

Check Apache Status Using Apache2ctl

Check Apache Status Using Apache2ctl

Alternatively, use the URL below to view the Apache web server status information from a graphical web browser:

http://localhost/server-status
OR
http:SERVER_IP/server-status

3. ps Utility

ps is a utility which shows information concerning a selection of the active processes running on a Linux system, you can use it with grep command to check Apache service uptime as follows.

Here, the flag:

  • -e – enables selection of every processes on the system.
  • -o – is used to specify output (comm – command, etime – process execution time and user – process owner).
# ps -eo comm,etime,user | grep apache2
# ps -eo comm,etime,user | grep root | grep apache2
OR
# ps -eo comm,etime,user | grep httpd
# ps -eo comm,etime,user | grep root | grep httpd

The sample output below shows that apache2 service has been running for 4 hours, 10 minutes and 28 seconds (only consider the one started by root).

Check Apache Uptime

Check Apache Uptime

Lastly, check out more useful Apache web server guides:

    1. 13 Apache Web Server Security and Hardening Tips
    2. How to Check Which Apache Modules are Enabled/Loaded in Linux
    3. 5 Tips to Boost the Performance of Your Apache Web Server
    4. How to Password Protect Web Directories in Apache Using .htaccess File

In this article, we showed you three different ways to check Apache/HTTPD service uptime on a Linux system. If you have any questions or thoughts to share, do that via the comment section below.

Source

WP2Social Auto Publish Powered By : XYZScripts.com