Installing LAMPP stack on Centos 7

by George Damian , 6 months ago

In the following article I will guide you through the process of setting up a fresh LAMP environment on a Centos 7 server with Apache, PHP 7 and MariaDB.

I chose a DigitalOcean droplet for this server but you can use whatever hosting provider you, since the setup steps are pretty much the same for all hosting providers. As shown in the image below, I chose a 2GB of RAM, single CPU and  50GB of SSD for $10 a month.

rp3r6GZ.png

Create Dropplet and access credentials

Before hitting that create button, don’t forget to create a set of SSH Keys and add it to your droplet  if you want to login to your server via SSH Keys. In order to create the SSH Keys you can follow the Windows tutorial or Linux/MacOS tutorial.

As the Windows tutorial wasn’t quite matching my Windows 10 config, I had to improvise a bit, by doing the following:

  •  Generate the keys with following commands instead of PuttyGen
  • cd C:\Users\Qdev\.ssh
  • ssh-keygen -t rsa
  • Import the generated private key into PuttyGen and export the private key again as .ppk
  • Load up the PuttyGen generated .ppk file into Putty, add your user and IP and you are ready to go

I have decided to use regular login as fallback, so I had to set the PasswordAuthentication Yes parameter inside  /etc/ssh/sshd_config and restart the ssh daemon via service sshd restart. Now that you are here, as a additional security measure, you can also disable root login by updating the line PermitRootLogin no

Either way you choose to use your server ( SSH Keys or Regular credentials ), after initial login, don’t forget to create a privileged user, and use that one instead of root for further usage:

 

adduser dev
passwd dev
gpasswd -a dev wheel
usermod -d /var/www/domain.com username #( change homedir for easier access if using SFTP )

 

Prequisites

 I personally like nano as my file editor, so on each fresh system I start by installing it. You can ignore this step if you use another editor:

sudo yum install nano

Another thing I will do with this server, is to assingn a domain name to it, so then we can easily access the web server and even the other services by pointing to it instead of the IP address. This can be done by updating your domain  nameservers, making point to digitalocean nameservers, and then in the digitalocean panel, you will need to park your domain, as in the picture below.

OquFNK9.png

GFt2CPN.png

Installing the LAMP Stack

We will now start installing the LAMP Stack, including PHP 7.2, MariaDB, Apache and couple additional security related programs.

1)      Install PHP 7.2

sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum install yum-utils
sudo yum-config-manager --enable remi-php72
sudo yum -y install php php-opcache
sudo yum -y install php-mysqlnd php-pdo php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-soap curl curl-devel

 

2)      Install MariaDB

sudo yum -y install mariadb-server mariadb
sudo systemctl start mariadb.service
sudo systemctl enable mariadb.service
sudo mysql_secure_installation


 Then when the mysql installation prompt will start, you will just have to go with these simple options:


Enter current password for root (enter for none): Just press enter

New password: Root Pass

Re-enter new password: Root Pass

Remove anonymous users? [Y/n] Y

Disallow root login remotely? [Y/n] Y

Reload privilege tables now? [Y/n] Y

 

After installation is complete, what I usually do instead of using softs like PHPMyAdmin, is I create a mysql user with remote access so I can manage the databases via clients like HeidiSQL. Run the command below and  enter the root password entered in the steps above.

 

mysql –u root –p 


This will create a user with access over all DBs and will only be allowed to connect from specified IP address. To allow remote access from any IP, use a wildcard (%)

GRANT ALL PRIVILEGES ON *.* TO 'user'@IP_ADDRESS' IDENTIFIED BY 'password' WITH GRANT OPTION;


Then if you want to use another MySql user for your actual web apps, create another like down below

GRANT ALL PRIVILEGES ON *.* TO 'app'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

 

3)      Install Apache

sudo yum -y install httpd #( should be already installed)
sudo systemctl start httpd.service
sudo systemctl enable httpd.service

 

Create a folder to serve your actual website:

sudo mkdir /var/www/html/domain.com
sudo chown -R apache:apache /var/www/html
sudo chmod -R 755 /var/www/html

 

Add the Apache virtualhosts:

sudo mkdir /etc/httpd/sites-enabled && sudo nano /etc/httpd/conf/httpd.conf

Then at the end of that configuration file, add the following line  IncludeOptional sites-enabled/*.conf


After you've addded that line, it's time to create a new virtualhost file for our domain, so we will start by creating a new file like this one:

sudo nano /etc/httpd/sites-enabled/domain.com.conf

 

 And inside this file you will need to add something like this:


<VirtualHost *:80>
    ServerName www.domain.com
    ServerAlias domain.com
    DocumentRoot  /var/www/html/domain.com
</VirtualHost>

<Directory /var/www/html/domain.com>
 Options +FollowSymLinks
 RewriteEngine On
</Directory>

 Save that file and restart the Apache server with sudo apachectl restart. You can then repeat this procedure to serve as many domains you want.

 

 Additonal security implementations


1) Fail2ban

 Fail2ban will automatically ban continuous failed SSH logins, in the case you chose not to use SSH keys.

sudo yum install fail2ban
sudo systemctl enable fail2ban
sudo nano /etc/fail2ban/jail.local

 And inside the config file, you can add the following rules or update them as you wish:

[DEFAULT]
# Ban hosts for one hour:
bantime = 3600
 
# Override /etc/fail2ban/jail.d/00-firewalld.conf:
banaction = iptables-multiport
 
[sshd]
enabled = true
 
 
ignoreip = 127.0.0.1/8 81.89.2.104
findtime = 600
maxretry = 3

ignoreip = 127.0.0.1/8

 

2)  Mod_evasive

Mod_evasive is an Apache module that will ban abusive HTTP requests made by users. This will be able to handle low to moderate DDOS attacks on your server.

sudo yum install mod_evasive –y
sudo nano /etc/httpd/conf.d/mod_evasive.conf

Then to get you started, here are some rules to get you started:

DOSHashTableSize   3097
DOSPageCount        20
DOSSiteCount       100
DOSPageInterval    1
DOSSiteInterval     1
DOSBlockingPeriod  120

 

3)  Install SSL with CertBot

SSL is a must these days, so grab your certificates using Certbot and following commands

sudo yum install certbot-apache
sudo certbot –apache

When you are asked about domains to install the certificates for, leave blank for all of them. In order to automatically renew your certificates, let's add a cron rule to renew them once 3 months, so open up the crontab with sudo nano /etc/crontab and add the following line:

5 8 * * 0 root certbot renew --quiet > /dev/null 2>&1

This should get your data secured.


Now if everything worked well, you should have your own LAMP server ready to go! This should be enough for your favourite PHP powered apps like Wordpress/Joomla/Drupal or PHP Frameworks like Laravel/Symfony/CakePHP.




Register and post a comment

Latest articles

Introduction to cloud computing

In the past decades, hard drives were the major storage device for data and information. And should any disaster occur, the entire data are lost forever – no means of retrieval whatsoever.  No wonder most businesses do not rely on hard drives as storage means anymore. 

Have you ever wondered how businesses – small, medium, and big businesses store their data? Well, the answer is the ‘cloud’.

Okay, that sounds strange. Cloud is a term which simply means ‘online’. Information said to be stored in the cloud are those information stored online.
Cloud computing, which is also known as security in the cloud, is a sub-category of a larger body, information security, which employs different sets of technologies in the protection of data and information stored online.

Thanks to technology, most organizations (70 % as recorded by the Cloud Security Agency, CSA.) across the globe, now operates in the cloud – i.e. run their programs online and store their data and information online too. So much safer I must add. 

As safe as cloud computing may be, it also has a few drawbacks. Just before then, let’s see some of the benefits of cloud computing to businesses – small, medium, and big businesses alike.

Benefits of Cloud Computing

Cloud computing or security in the cloud provides its users with lots of benefits. Some of which are:

  • Quick and Easy Access to Information: Cloud computing provides its users with easy access to data and information as they are stored on a single desktop computer. Any authorized party can easily access the company’s data anywhere across the globe.
  • It Ensures Better Business Continuity: Retrieving data after a natural disaster is made possible with cloud computing. These natural disasters – earthquake, flood, fire outbreak, power outage, etc., are bound to occur at some point in time but have no fear as your data are secured in the cloud. You just have to log in from a new device and retrieve the vital data needed for continuity of your business. 
  • Enhanced Service: Incorporating the cloud computing system enables data sharing among users. This helps increases the quality of your customer service as you can integrate different software and features to serve them better.
  • It Lowers IT Cost: Before now, a set of individuals are employed to manage a company’s data and programs. Cloud computing serves most of the functions such as software upgrade, data backups, and patches; as such you will need just a few IT staffs. Consequently, saving you more revenue.   
  • Drawbacks of Cloud Computing
  • Although securing your data in the cloud provides you with lots of benefits, it also exposes you to some risk. This is why it is advisable to pay attention to security on the cloud (securing your online account) as much as security in the cloud.
  • Some of the security concerns associated with cloud computing include;
  • Data Breaches
  • Denial of Service (DOS) attack
  • Hijacking of account 
  • Data loss
  • Malware injection

Useful Tips for Securing your Data in the Cloud

Most organizations have been victims of different cybercrimes because they pay less attention to security on the cloud. Security on the cloud is a topic of concern among small, medium, and big firms. Sadly, the individual businesses have got more roles to play than the service providers.
Here are some useful tips you can employ in securing your data in the cloud.

  1. Be sure to use strong passwords on your account. It is better to make your password as long as possible. This makes it difficult for cybercriminals to guess correctly. Also, the password should be alphanumeric. Addition of symbols is safer too.
  2. A good understanding of social engineering attacks is necessary for the safety of your data in the cloud. Employees and employers are to be educated on the various forms of phishing and social engineering attacks so that they know how to deal with such attacks when they occur.
  3. Thankfully, most cloud software now requires the use of two-factor authentication, i.e. the use of other forms of verification besides password and username. This makes it difficult for cybercriminals to hijack your cloud account.
  4. Anti-malware or anti-virus is also useful in protecting your data online. In fact, your business is at risk without anti-malware software in your devices – phones, computers, tablets, etc. Virus come into your devices through different means, it could be through an email, a link, or an app. This anti-virus software help protect your devices from such attacks.


Queuing emails in Laravel with Background Jobs

So most of the web apps nowadays are featuring email notifications, newsletters and all kinds of different email implementations.  Laravel eases up the process a lot with its suit of tools that allows you to send email via any driver you wish, template and customize your emails and even queue them for later execution.


The queue functionality comes in handy in particular when you want to speed up up your application by not having to wait for server response when doing requests that are sending emails. This basically allows emails to be sent asynced on the server side. Couple examples of use cases:


  • When for example pressing on the register button, the UI won’t have to wait for the server response, while the server is sending the email.
  • When your server / service sends your email to slow.
  • When sending large number of emails, maybe even bypassing Mailgun’s 100 emails / hour limit.


But enough with the long talk and let’s get to business. For this particular example, I have used Laravel 5.4, but this should be pretty much the same on newer and even older versions. Let's get started!

Step 1. For easier to edit code in the future, we will use a Service provider to easily dispatch email actions across our controllers. To get the based of your provider, you can run the following command

php artisan make:provider EmailProvider

After the base file has been created, make sure it looks something like this

<?php
namespace App\Providers;
use App\Jobs\SendEmail;
use Illuminate\Support\ServiceProvider;
class EmailProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     *
     * Generic email template method
     *
     * @param $email
     * @param $header
     * @param $content
     */
    public static function sendEmail($subject, $title, $content){
        dispatch(new SendEmail($subject,$title,$content));
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Step 2. Create a Laravel Job

php artisan make:job SendEmail

After the base file has been created, make sure it looks something like this

<?php
namespace App\Jobs;
use App\Mail\GenericEmail;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mail;
class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $emailSubject,$emailTitle,$emailContent;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($emailSubject,$emailTitle,$emailContent)
    {
        //
        $this->emailSubject = $emailSubject;
        $this->emailTitle = $emailTitle;
        $this->emailContent = $emailContent;
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        Mail::to($user->email)->later(Carbon::now()->addMinute(1), new GenericEmail($this->emailSubject,$this->emailTitle,$this->emailContent));
    }
}

Step 3. Create a Mailable Class

php artisan make:mail GenericEmail


<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class GenericEmail2 extends Mailable
{
    use Queueable, SerializesModels;
    public $subject = 'Mass email';
    public $title = 'Email header';
    public $content = 'Email content';
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($emailTitle,$emailTitle,$emailContent)
    {
        //
        $this->subject = $emailTitle;
        $this->title = $emailTitle;
        $this->content = $emailContent;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->subject($this->subject)
            ->view('emails.template');
    }
}

Step 4. Create an email template file in a directory like resources/views/emails/template.blade.php with a content like


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml" style="font-size: 100%; font-family: 'Avenir Next', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.65; margin: 0; padding: 0;">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width" />
<!-- For development, pass document through inliner -->
  </head>
  <body style="font-size: 100%; font-family: 'Avenir Next', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.65; width: 100% !important; height: 100%; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; background: #efefef; margin: 0; padding: 0;">
  <h2>{!!$emailTitle!!}</h2>
  <p>{!!$content!!}</p>
  </body>
</html>

Now you should be be able to send queued emails from wherever you want in your app with something like

EmailProvider::sendGlobal(‘This is a test email’,’Welcome friend’,’Just testin things around’);


But before actually sending the emails, we will need to configure laravel and our server to run the service worker continuously and send actually send the previously queued emails.
Now, there are many options you can chose from when it comes to service worker drivers, including self hosted worker, AWS or Redis.

In this example we will work with a self hosted worker, so let’s start by creating the tables it needs to store the tables.

php artisan queue:table
php artisan migrate


Then open up your dot env file and make sure the following entry is present
QUEUE_DRIVER=database

Bonus: Installing service supervisor

Now, in real life usage, on sites with decent amounts of traffic the service is very likely to fail from time to time, so Supervisor makes sure the worker gets restarted if this happens.

This time I am using a Centos system, but the commands should be relatively similar on *nix systems.

easy_install supervisor
yum install supervisor
echo_supervisord_conf > /etc/supervisord.conf
nano /etc/supervisord.conf

And add following content:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /var/www/html/artisan queue:work --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
numprocs=2

Create log file

sudo mkdir -p /var/log/supervisor/laravel/
sudo touch /var/log/supervisor/laravel/worker.log

Start the service

sudo service supervisord start
sudo supervisorctl reload

And enable it at system start

systemctl enable supervisord

If you have config changes

supervisorctl reread
supervisorctl update
supervisorctl restart all

That’s it for this tutorial! If everything went well, then your Laravel email setup should be able to handle all the emails you need.

If you are having any questions, don’t hesitate to ask me via a comment!

What is dev burnout and how to overcome it

The job description of a developer goes beyond writing codes. We also look after databases and monitor sever-based systems; these are time demanding tasks that most of us have little to no private life. Although it looks like we have our lives after work but in reality our job goes beyond office hours. Most of us have an IT setup in our homes where we spend the supposed free time working tirelessly on virtualizing servers, programming language, designing theories or testing out new database. We virtually do nothing else than stare at the computer day and night. No wonder burnout is common amongst dedicated programmers even at young age.

Developer’s burnout is basically that point in a programmer’s career where he gets exhausted and wishes to do just about anything other than his job. Yes I love my job, but there are times I wish I was not a programmer.


Causes of Burnout

Burn out is caused by several reasons but the most common of these reasons is prolonged state of intense stress from a ‘death march task’ ( a high-stake task that requires large amount of personal sacrifice and seem impossible to complete). It tends to grow gradually; one step at a time till you lost all of the passion you have for your job and start contemplating on quitting. Some other causes of burnout include;


  • Doing same task over and over without a break, from month to month and year to year. This can become very tiresome and boring leading to lost of passion and zealousness for your job.
  • Mental fatigue can also be a cause as programming is highly cognitive, stressful and intense. 
  • Working constantly to tight deadlines is another reason for burnout. Everything is a rush. As programmers, we often have more than one deadlines approaching and all you can think of is how to quickly finish up so you beat the deadline. This is unhealthy and can lead to a mental breakdown
  • Working long hours on end for months or maybe years. Work tends to invade our private lives, no night rest or weekend breaks. This eventually leads to overbearing stress that makes you seek anything but your job.


How to Avoid Burnout


  • Do not Overwork: The first and most important tip on overcoming burnout is ‘do not overwork’. Avoid it like a plague. Generally, productivity decreases as the time spent on a task increases. Why then do we spend all those hours overworking our brains? You end up doing more harm than good. Quit overworking.
  • Pomodoro Technique: This involves taking a break at intervals while working, say 25 minutes of focused work then 5 minutes of rest. By doing so, you ease yourself of built up tension and become more productive even.
  • Exercises: Yes the job is tasking and demanding but you do not have to stay glued to your computer all day. Do a work out, it must not necessarily involve going to the gym. You could do pushups, sit ups, weight lifting, take a walk, anything, just stay active and keep moving.
  • As programmers it helps to take a break from work and experiment or play on other work related stuffs that does not involve fear of failure. You end up learning something new and resting at same time. 
  • You could also attend conferences and meetups. You gain a lot by just listening to other programmers talk. Hearing others experiences helps motivate you and increases your focus on your job.
  • Endeavour to take breaks and indulge in other passions. Programming is not your only passion; indulge in others so you do not get bored of work.
  • Working on same tech or project over and over can become tiring and boring, as such, take up new projects, anything to help rejuvenate you.


Conclusion

Leading a healthy work life as programmers takes a lot of commitment and conscious efforts. I advice we quit this cult of ‘overworking’. Not spending all day on coding and work related things does not make you the least dedicated in your organization. Let’s strive to strike a balance between our work and our private life. Truth is, when you involve yourself in other activities you learn better from real life and incorporate these experiences into your inventions. Don not kill your passion for coding by overworking yourself. Say no to over working, eat and sleep well, lead a healthy life style and you will have no burn out experience.