Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aldibier/6146761 to your computer and use it in GitHub Desktop.
Save aldibier/6146761 to your computer and use it in GitHub Desktop.
Pasos de instalación para un servidor LAMP con configuraciones optimizadas para Drupal
--------------------
Información
--------------------
- Ubuntu 12.04 LTS
- Linode
- MEM: 1GB
- CPU: 8 CORES
-------------------
Instalación:
-------------------
Ingrese con el usuario Root, si no lo tiene use "sudo"
1. Creación de usuario distinto a root
# adduser admin
2. Añadir el nuevo usuario a sudo
# nano /etc/sudoers
Si encuentra la siguiente línea no necesita hacer nada, de lo contrario debe crearla, esto le dará acceso de sudo a todos los usuarios que están dentro del grupo admin.
# Members of the admin group may gain root privileges
%admin ALL=(ALL:ALL) ALL
Importante: que la instrucciòn entre parétesis este tal cual ya que asi no pedirá contraseña cuando se use sudo
3. Generar la llave de acceso al servidor
Estos pasos los debe realizar en su máquina local
$ ssh-keygen -t rsa -b 2048 -v
Le preguntará por el nombre del archivo, inserte el nombre que prefiera, en este caso, he usado el nombre "mykey-replace", esto generará un archivo mykey-replace.pub y el archivo mykey-replace sin una extensión, ese archivo renombrelo a mykey-replace.pem los archivos son creados en el directorio donde se encuentre en la cosnsola, en el proceso le preguntará por una palabra clave, esto es para asegurar el certificado en la máquina local, puede ignorar esta opción si considera que el equipo donde se va a usar la llave es seguro.
3. Transferir la llave de usuario al servidor
Desde el equipo que usará para conectarse, transfiera la llave a la carpeta del usuario que creó en el servidor
$ scp /home/mylocaluser/.ssh/mykey-replace.pub myuser@myserver:~
4. Incluya la llave al servidor como autorizada
Ingrese desde su equipo al servidor
$ ssh myuser@myserver
En el servidor quiźas tenga que crear la carpeta .ssh
$ mkdir ~/.ssh
$ cat key-replace.pub >> ~/.ssh/authorized_keys
Regrese a la consola de suequipo y pruebe nuevamente la conexión, si todo salió bien en esta ocasión no le solicitará la contraseña
$ ssh myuser@myserver -i key-replace.pem
5. Configuración del Acceso SSH al servidor
$ sudo nano /etc/ssh/sshd_config
Cambie a las siguientes directivas para no permitir el acceso por SSH al usuario Root, para eso usamos los usuarios con permisos de sudo y también restringir el acceso a solo si se tiene una llave autorizada.
PermitRootLogin no
PasswordAuthentication no
$ sudo /etc/init.d/ssh restart
--- hostname ---
$ sudo nano /etc/hostname
myservername
$ sudo hostname myservername
$ sudo nano /etc/hosts
127.0.0.1 localhost myserver
--- Apache + PHP5-FPM ---
$ sudo apt-get update
$ sudo apt-get install apache2
revisa que el paquete apache2-mpm-worker se instale si no está, lo puede instalar de la siguiente forma
$ sudo apt-get install apache2-mpm-worker
$ sudo apt-get install libapache2-mod-fastcgi php5-fpm php5 php5-curl php5-gd php5-imagick php-apc php5-mysql php-pear
$ sudo a2enmod actions fastcgi alias rewrite
$ sudo service apache2 restart
Cambiar PHP-FPM para que no se gestione por puerto sino por socket
$ sudo nano /etc/php5/fpm/pool.d/www.conf
;listen = 127.0.0.1:9000
listen = /var/run/php5-fpm.sock
$ sudo /etc/init.d/php5-fpm restart
# sudo nano /etc/apache2/conf.d/php5-fpm.conf
<IfModule mod_fastcgi.c>
AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
</IfModule>
$ sudo service apache2 restart
--- Tune Apache ---
The problem
By default apache2 is configured to support 150 concurrent connections. This forces all parallel requests beyond that limit to wait. Especially if, for example, active sync clients maintain a permanent connection for push events to arrive.
The solution
This is an example configuration to provide 800 concurrent connections. Please ensure that your apache is using the mpm_worker module. This allows us to serve lots of concurrent connections by using less RAM than with mpm_prefork as we are going to start much less processes.
<IfModule mpm_worker_module>
ServerLimit 25
StartServers 10
MinSpareThreads 75
MaxSpareThreads 250
ThreadLimit 64
ThreadsPerChild 32
MaxClients 800
MaxRequestsPerChild 10000
</IfModule>
Short explanation of the parameters:
ServerLimit Declares the maximum number of running apache processes. If you change this value you have to restart the daemon.
StartServers The number of processes to start initially when starting the apache daemon.
MinSpareThreads/MaxSpareThreads This regulates how many threads may stay idle without being killed. Apache regulates this on its own very well with default values.
ThreadsPerChild How many threads can be created per process. Can be changed during a reload.
ThreadLimit ThreadsPerChild can be configured as high as this value during runtime. If you change this value you have to restart the daemon.
MaxClients This declares how many concurrent connections we provide. Devided by ThreadsPerChild you get the suitable ServerLimit value. May be less than ServerLimit * ThreadsPerChild to reserve some resources that can be engaged during runtime with increasing MaxClients and reloading the configuration.
MaxRequestsPerChild Defines the number of Connections that a process can handle during its lifetime (keep-alives are counted once). After that it will be killed. This can be used to prevent possible apache memory leaks. If set to 0 the lifetime is infinite.
For further information on these parameters see http://httpd.apache.org/docs/2.2/mod/worker.html and http://httpd.apache.org/docs/2.2/mod/mpm_common.html.
--- MYSQL---
$ sudo apt-get install mysql-server mysql-client
7. Instalación Git
$ sudo aptitude install git
----------------------
CONFIGURACIÓN
----------------------
Permitir que el usuario creado pueda escribir en la carpeta de publicación de apache, aprovechamos el grupo www-data
$ sudo groupadd www-users
$ sudo usermod -a -G www-users myuser
$ sudo chown -R :www-users /var/www
$ sudo chmod -R g+rwX /var/www
$ sudo chmod g+s /var/www
¡Importante!: Si después de estos cambios quiere crear archivos debería salir de la sesión y luego volver a entrar para que tengan efecto.
Configuración de nano para que no muestre el error con el archivo .nano_history
$ sudo nano /etc/nanorc
# set historylog
$ mkdir /var/www/default
$ mkdir /var/www/vhost
Edita el archivo de configuración del virtual host por defecto para que apunte al directorio /var/www/html
$ sudo nano /etc/apache2/sites-available/default
DocumentRoot /var/www/default
<Directory /var/www/default>
--- PHP ---
Instalación de PECL Upload Progress
$ sudo apt-get install build-essential
$ sudo pecl install uploadprogress
$ sudo nano /etc/php5/fpm/conf.d/uploadprogress.ini
extension=uploadprogress.so
-------------------------
HARDENING
-------------------------
--- En PHP ---
$ sudo nano /etc/php5/fpm/php.ini
expose_php = Off
--- En MySQL ---
$ sudo mysql_secure_installation
- Change the root password? [Y/n] n
- Remove anonymous users? [Y/n] y
- Disallow root login remotely? [Y/n] y
- Remove test database and access to it? [Y/n] y
- Reload privilege tables now? [Y/n] y
--- En Apache ---
$ sudo nano /etc/apache2/conf.d/security
ServerTokens Prod
ServerSignature Off
------------------------
DRUPAL
------------------------
--- Instalación de Drush ---
$ sudo pear channel-discover pear.drush.org
$ sudo pear install drush/drush
$ cd ~
$ wget -c http://download.pear.php.net/package/Console_Table-1.1.3.tgz
$ tar -zxvf Console_Table-1.1.3.tgz
$ sudo cp -rp Console_Table-1.1.3 /usr/share/php/drush/lib/
$ drush dl registry_rebuild
--- Probar Drupal ---
$ cd /var/www/vhost/
$ drush dl drupal
Esto descargará la versión mas reciente de Drupal, en mi caso drupal-7.22
--- Configuración Por sitio ---
$ sudo nano /etc/apache2/sites-available/mysite
<VirtualHost *:80>
ServerName mysite.com
ServerAlias www.mysite.com
ServerAdmin nickname@dominio.com
DocumentRoot /var/www/vhost/drupal-7.22
<Directory /var/www/vhost/drupal-7.22>
Options FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/mysite.error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/mysite.access.log combined
</VirtualHost>
$ sudo a2ensite mysite
$ sudo service apache2 reload
================ REDIS ===========
$ sudo apt-get install redis-server
$ sudo update-rc.d redis-server disable
$ sudo nano /etc/init/redis-server
description "redis server"
start on runlevel [23]
stop on shutdown
exec sudo -u redis /usr/bin/redis-server /etc/redis/redis.conf
respawn
$ sudo start redis-server
$ sudo restart redis-server
$ sudo stop redis-server
Download an unzip the phpredis library in the libraries folder
https://github.com/nrk/predis
$ nano settings.php
define('PREDIS_BASE_PATH', DRUPAL_ROOT . '/sites/mysite/libraries/predis-0.8/lib/');
$conf['redis_client_interface'] = 'Predis';
$conf['cache_backends'][] = 'sites/mysite/modules/contrib/redis/redis.autoload.inc';
$conf['cache_class_cache'] = 'Redis_Cache';
$conf['cache_class_cache_form'] = 'Redis_Cache';
$conf['cache_class_cache_views'] = 'Redis_Cache';
$conf['cache_class_cache_page'] = 'Redis_Cache';
$conf['cache_class_cache_menu'] = 'Redis_Cache';
$conf['cache_class_cache_path'] = 'Redis_Cache';
$conf['cache_class_cache_entity_node'] = 'Redis_Cache';
$conf['cache_class_cache_entity_taxonomy_term'] = 'Redis_Cache';
$conf['cache_class_cache_entity_taxonomy_vocabulary'] = 'Redis_Cache';
$conf['cache_class_cache_entity_file'] = 'Redis_Cache';
$conf['cache_class_cache_entity_user'] = 'Redis_Cache';
$conf['cache_class_cache_filter'] = 'Redis_Cache';
$conf['cache_class_cache_admin_menu'] = 'Redis_Cache';
$conf['cache_class_cache_bootstrap'] = 'Redis_Cache';
$conf['lock_inc'] = 'sites/mysite/modules/contrib/redis/redis.lock.inc';
$conf['redis_client_base'] = 1; //Change Database number
$conf['cache_class_cache_field'] = 'Redis_Cache';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment