How to Install Nginx with PHP and MySQL (LEMP Stack) on CentOS 7.6
This tutorial exists for these OS versions
On this page
This tutorial shows how you can install Nginx on a CentOS 7 server with PHP support (through PHP-FPM) and MySQL (MariaDB) support.
What is LEMP?
Nginx (pronounced "engine x") is a free, open-source, high-performance HTTP server. Nginx is known for its stability, rich feature set, simple configuration, and low resource consumption.
LEMP Prerequisites
In this tutorial, I will use the hostname server1.example.com with the IP address 192.168.1.100. These settings might differ for you, so you have to replace them where appropriate.
I will use the nano editor in this tutorial to edit configuration files. Nano can be installed like this.
yum -y install nano
I recommend having a firewall installed. If you do not have firewalld installed yet and want to use a firewall, then install it with these commands:
yum -y install firewalld
start the firewall and enable it to be started at boot time.
systemctl start firewalld.service
systemctl enable firewalld.service
Next, open your SSH port to ensure that you will be able to connect to the server by SSH.
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --reload
Enabling Additional CentOS Repositories
The latest Nginx is not available from the official CentOS repositories, so we include the repository of the Nginx project to install it:
nano /etc/yum.repos.d/nginx.repo
[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=0 enabled=1
Installing MySQL (MariaDB)
First, we install MariaDB as MySQL replacement. MariaDB is a free fork of MySQL. Run this command on the shell to install the MariaDB database server:
yum -y install mariadb mariadb-server net-tools
Then we create the system startup links for MariaDB (so that it starts automatically whenever the system boots) and start the MariaDB server:
systemctl enable mariadb.service
systemctl start mariadb.service
Now check that networking is enabled. Please note that the MraiDB service is named mysql as it is a compatble database server. Run
netstat -tap | grep mysql
It should show something like this:
[root@server1 ~]# netstat -tap | grep mysql
tcp 0 0 0.0.0.0:mysql 0.0.0.0:* LISTEN 19842/mysqld
Run:
mysql_secure_installation
to set a password for the user root (otherwise, anybody can access your MySQL database!):
[root@example ~]# mysql_secure_installation
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
Set root password? [Y/n] <-- ENTER
New password: <-- yourrootsqlpassword
Re-enter new password: <-- yourrootsqlpassword
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] <-- ENTER
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] <-- ENTER
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] <-- ENTER
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] <-- ENTER
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
[root@example ~]#
[root@server1 ~]# mysql_secure_installation
Installing Nginx
Nginx is available as a package from nginx.org which we can install like this:
yum -y install nginx
Then we create the system startup links for nginx and start it:
systemctl enable nginx.service
systemctl start nginx.service
There are chances that you get an error that port 80 is already in use, the error message will be like this:
[root@server1 ~]# service nginx start
Starting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
[FAILED]
[root@server1 ~]#
This means that another web server (probably Apache) is already running on this server. Stop the Apache service and then start the service for NGINX:
systemctl stop httpd.service
yum remove httpd
systemctl disable httpd.service
Then try to start Nginx again.
systemctl start nginx.service
Open the HTTP and HTTPS ports in the firewall
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload
The resulting output on the shell will look like this:
[root@example ~]# firewall-cmd --permanent --zone=public --add-service=http
success
[root@example ~]# firewall-cmd --permanent --zone=public --add-service=https
success
[root@example ~]# firewall-cmd --reload
success
[root@example ~]#
Type in your web server's IP address or hostname into a browser (e.g. http://192.168.1.100), and you should see the Nginx welcome page:
Installing PHP
We can make PHP 5 work with Nginx through PHP-FPM (FastCGI Process Manager). PHP-FPM is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites. We can install php-fpm together with php-cli and some PHP5 modules like php-mysql which you need if you want to use MySQL from your PHP scripts as follows:
yum -y install php-fpm php-cli php-mysql php-gd php-ldap php-odbc php-pdo php-pecl-memcache php-pear php-mbstring php-xml php-xmlrpc php-mbstring php-snmp php-soap
APC is a free and open PHP opcode cacher for caching and optimizing PHP intermediate code. It's similar to other PHP opcode cachers, such as eAccelerator and Xcache. It is strongly recommended to have one of these installed to speed up your PHP page.
I will install APC from PHP pecl repository. PECL requires the Centos Development tools to be installed to compile the APC package.
yum -y install php-devel
yum -y groupinstall 'Development Tools'
and install APC:
pecl install apc
[root@example ~]# pecl install apc
downloading APC-3.1.13.tgz ...
Starting to download APC-3.1.13.tgz (171,591 bytes)
.................done: 171,591 bytes
55 source files, building
running: phpize
Configuring for:
PHP Api Version: 20100412
Zend Module Api No: 20100525
Zend Extension Api No: 220100525
Enable internal debugging in APC [no] : <-- ENTER
Enable per request file info about files used from the APC cache [no] : <-- ENTER
Enable spin locks (EXPERIMENTAL) [no] : <-- ENTER
Enable memory protection (EXPERIMENTAL) [no] : <-- ENTER
Enable pthread mutexes (default) [no] : <-- ENTER
Enable pthread read/write locks (EXPERIMENTAL) [yes] : <-- ENTER
building in /var/tmp/pear-build-rootVrjsuq/APC-3.1.13
......
Then open /etc/php.ini and set cgi.fix_pathinfo=0:
nano /etc/php.ini
[...] ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting ; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting ; of zero causes PHP to behave as before. Default is 1. You should fix your scripts ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED. ; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo cgi.fix_pathinfo=0 [...]
(Please read http://wiki.nginx.org/Pitfalls to find out why you should do this.)
and add the line:
[...] extension=apc.so
at the end of the /etc/php.ini file.
In addition to that, in order to avoid timezone errors like
[28-June-2016 14:21:01] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2
... in /var/log/php-fpm/www-error.log when you call a PHP script in your browser, you should set date.timezone in /etc/php.ini:
[...] [Date] ; Defines the default timezone used by the date functions ; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone date.timezone = "Europe/Berlin" [...]
You can find out the correct timezone for your system by running:
cat /etc/sysconfig/clock
[root@server1 nginx]# cat /etc/sysconfig/clock
ZONE="Europe/Berlin"
[root@server1 nginx]#
Next, create the system startup links for php-fpm and start it:
systemctl enable php-fpm.service
systemctl start php-fpm.service
PHP-FPM is a daemon process (with the init script /etc/init.d/php-fpm) that runs a FastCGI server on port 9000.
Configuring Nginx
The nginx configuration is in /etc/nginx/nginx.conf which we open now:
nano /etc/nginx/nginx.conf
First (this is optional) you can increase the number of worker processes and set the keepalive_timeout to a reasonable value:
[...] worker_processes 4; [...] keepalive_timeout 2; [...]
The virtual hosts are defined in server {} containers in the /etc/nginx/conf.d directory. Let's modify the default vhost (in /etc/nginx/conf.d/default.conf) as follows:
nano /etc/nginx/conf.d/default.conf
[...] server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/log/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm index.php; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root /usr/share/nginx/html; try_files $uri =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } }
server_name _; makes this a default catchall vhost (of course, you can as well specify a hostname here like www.example.com).
In the location / part, I've added index.php to the index line. root /usr/share/nginx/html; means that the document root is the directory /usr/share/nginx/html.
The important part for PHP is the location ~ \.php$ {} stanza. Uncomment it to enable it. Change the root line to the web site's document root (e.g. root /usr/share/nginx/html;). Please note that I've added the line try_files $uri =404; to prevent zero-day exploits (see http://wiki.nginx.org/Pitfalls#Passing_Uncontrolled_Requests_to_PHP and http://forum.nginx.org/read.php?2,88845,page=3). Please make sure that you change the fastcgi_param line to fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; because otherwise, the PHP interpreter won't find the PHP script that you call in your browser ($document_root translates to /usr/share/nginx/html because that's what we have set as our document root).
PHP-FPM is listening on port 9000 on 127.0.0.1 by default, therefore we tell Nginx to connect to 127.0.0.1:9000 with the line fastcgi_pass 127.0.0.1:9000;. It is also possible to make PHP-FPM use a Unix socket - I will describe this in chapter 7.
Now save the file and reload Nginx:
systemctl restart nginx.service
Now create the following PHP file in the document root /usr/share/nginx/html...
nano /usr/share/nginx/html/info.php
<?php phpinfo(); ?>
Now we call that file in a browser (e.g. http://192.168.1.100/info.php):
As you see, PHP 5 is working, and it's working through FPM/FastCGI, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5, including the MySQL module:
Making PHP-FPM use a Unix Socket
By default, PHP-FPM is listening on port 9000 on 127.0.0.1. It is also possible to make PHP-FPM use a Unix socket which avoids the TCP overhead. To do this, open /etc/php-fpm.d/www.conf...
nano /etc/php-fpm.d/www.conf
... and make the listen line look as follows:
[...] ;listen = 127.0.0.1:9000 listen = /var/run/php-fpm/php5-fpm.sock [...]
Then reload PHP-FPM:
systemctl restart php-fpm.service
Next, go through your Nginx configuration and all your vhosts and change the line fastcgi_pass 127.0.0.1:9000; to fastcgi_pass unix:/tmp/php5-fpm.sock;, e.g. like this:
vi /etc/nginx/conf.d/default.conf
[...]
location ~ \.php$ {
root /usr/share/nginx/html;
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
[...]
Finally, reload Nginx:
systemctl restart nginx.service
Download this CentOS 7 server as a virtual machine
This setup is available as a virtual machine download in ova/ovf format (compatible with VMWare and Virtualbox) for howtoforge subscribers.
Login details for the VM
- The root password is: howtoforge
- The password of the "administrator" user is: howtoforge
Please change both passwords on the first login.
- The IP address of the VM is 192.168.1.100
Links
- nginx: http://nginx.org/
- nginx Wiki: http://wiki.nginx.org/
- PHP: http://www.php.net/
- PHP-FPM: http://php-fpm.org/
- MySQL: http://www.mysql.com/
- CentOS: http://www.centos.org/