Como Instalar NGINX desde el código fuente en Ubuntu Server 14.04

Instalando NGINX desde el código fuente

Como en toda instalación lo primero es descargar el medio de instalación y en este caso es un pequeño archivo tar.gz que es el código fuente de nuestro servidor web, para obtenerlo debes ir a http://nginx.org/ y dar click en el enlace de la versión mas reciente del software, al momento de escribir esto es la versión 1.9.11. En esta página darías click precisamente en el enlace que diría ‘nginx-1.9.11’, pero recuerda, tu debes dar click en la versión que se muestre como la mas actual.

nginx install ubuntu server source code ubuntu mexicoEn en la página de descarga vas a buscar de nuevo ‘nginx-1.9.11’ en el apartado «Mainline version» y ahí descargarás el archivo nginx-1.9.11.tar.gz o la versión que corresponda al momento en que la descargues.

En este momento será bueno que inicies una sesión como super usuario así que debes ejecutar el comando:

sudo su -

Como se supone que estarás en un servidor Ubuntu 14.04 LTS vas a necesitar hacer esto en la terminal, así que vas a copiar ese enlace y vas a descargar el archivo en el servidor con el comando wget, si por alguna razón este comando no está disponible en tu servidor lo puedes instalar con el comando:

sudo apt-get install wget

Una vez que tengas en enlace puedes descargar el archivo del código fuente de NGINX, luego debes descomprimirlo y ubicarte dentro de la carpeta, hazlo con estos comandos:

wget http://nginx.org/download/nginx-1.9.11.tar.gz
tar zxf nginx-1.9.11.tar.gz
cd nginx-1.9.11/

Recuerda solo cambia la versión si hay una más reciente. Lo siguiente es configurar los módulos de NGINX y algunas variables como la ubicación de las rutas de configuración. Esto lo haces con un comando que es bastante extenso pero que también puede darte la flexibilidad de instalar solo los módulos que necesite tu página web, así como las rutas, el usuario, etc.

./configure --user=nginx --group=nginx --with-ld-opt='-Wl,-E,-Bsymbolic-functions -Wl,-z,relro' --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_addition_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module --with-http_sub_module --with-http_xslt_module --with-mail --with-mail_ssl_module

Este comando solo se encarga de configurar lo que se va a compliar y donde se instalarán los paquetes compilados o ejecutables, las rutas de configuración, etc. Puedes ver más detalles de lo que hace cada módulo en la documentación del proyecto y en particular en esta URL https://www.nginx.com/resources/admin-guide/installing-nginx-open-source/

En general siempre se van a instalar los módulos marcados como «default» y hay otros que son opcionales, puedes indicar que no deseas instalar un módulo «default» con el parámetro –without-modulo_default y agregar  un módulo opcional con el parámetro –with-modulo_opcional.

Por ejemplo si quieres agregar el módulo opcional http_mp4_module y quitar el módulo default http_geo_module podrías agregar estos parámetros:

--with-http_geo_module --without-http_geo_module

Una vez que definas los módulos que vas a agregar a tu servidor NGINX puedes adaptar el comando ./configure y ejecutarlo. Si todo sale bien debes ver algo como lo siguiente:

Configuration summary
+ using system PCRE library
+ using system OpenSSL library
+ md5: using OpenSSL library
+ sha1: using OpenSSL library
+ using system zlib library
+ using system libatomic_ops library

nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/sbin/nginx"
nginx modules path: "/usr/local/nginx/modules"
nginx configuration prefix: "/etc/nginx"
nginx configuration file: "/etc/nginx/nginx.conf"
nginx pid file: "/var/run/nginx.pid"
nginx error log file: "/var/log/nginx/error.log"
nginx http access log file: "/var/log/nginx/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp"

Estas rutas te van a ser de utilidad por lo que debes guardarlas. Lo siguiente que tienes que hacer es compilar, enlazar e instalar todo. Esto lo haces com el comando:

make && make install

Ahora solo debes esperar que se realice la compilación, cuando termine debes crear el archivo /etc/init.d/nginx con el que vas a arrancar o detener tu servidor nginx.

nano /etc/init.d/nginx

y copia el siguiente texto tal y como está:

#! /bin/bash

. /lib/lsb/init-functions
 
#------------------------------------------------------------------------------
#                               Consts
#------------------------------------------------------------------------------
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/sbin/
DAEMON=/usr/sbin/nginx
 
PS="nginx"
PIDNAME="nginx"				#lets you do $PS-slave
PIDFILE=$PIDNAME.pid                    #pid file
PIDSPATH=/var/run
 
DESCRIPTION="Nginx Server version 1.6.2"
 
RUNAS=root                              #user to run as
 
SCRIPT_OK=0                             #ala error codes
SCRIPT_ERROR=1                          #ala error codes
TRUE=1                                  #boolean
FALSE=0                                 #boolean
 
lockfile=/var/lock/subsys/nginx
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
 
#------------------------------------------------------------------------------
#                               Simple Tests
#------------------------------------------------------------------------------
 
#test if nginx is a file and executable
test -x $DAEMON || exit 0
 
# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
        . /etc/default/nginx
fi
 
#set exit condition
#set -e
 
#------------------------------------------------------------------------------
#                               Functions
#------------------------------------------------------------------------------
 
setFilePerms(){
 
        if [ -f $PIDSPATH/$PIDFILE ]; then
                chmod 400 $PIDSPATH/$PIDFILE
        fi
}
 
configtest() {
	$DAEMON -t -c $NGINX_CONF_FILE
}
 
getPSCount() {
	return `pgrep -f $PS | wc -l`
}
 
isRunning() {
        if [ $1 ]; then
                pidof_daemon $1
                PID=$?
 
                if [ $PID -gt 0 ]; then
                        return 1
                else
                        return 0
                fi
        else
                pidof_daemon
                PID=$?
 
                if [ $PID -gt 0 ]; then
                        return 1
                else
                        return 0
                fi
        fi
}
 
#courtesy of php-fpm
wait_for_pid () {
        try=0
 
        while test $try -lt 35 ; do
 
                case "$1" in
                        'created')
                        if [ -f "$2" ] ; then
                                try=''
                                break
                        fi
                        ;;
 
                        'removed')
                        if [ ! -f "$2" ] ; then
                                try=''
                                break
                        fi
                        ;;
                esac
 
                #echo -n .
                try=`expr $try + 1`
                sleep 1
        done
}
 
status(){
	isRunning
	isAlive=$?
 
	if [ "${isAlive}" -eq $TRUE ]; then
                echo "$PIDNAME found running with processes:  `pidof $PS`"
        else
                echo "$PIDNAME is NOT running."
        fi
 
 
}
 
removePIDFile(){
	if [ $1 ]; then
                if [ -f $1 ]; then
        	        rm -f $1
	        fi
        else
		#Do default removal
		if [ -f $PIDSPATH/$PIDFILE ]; then
        	        rm -f $PIDSPATH/$PIDFILE
	        fi
        fi
}
 
start() {
        log_daemon_msg "Starting $DESCRIPTION"
 
	isRunning
	isAlive=$?
 
        if [ "${isAlive}" -eq $TRUE ]; then
                log_end_msg $SCRIPT_ERROR
        else
                start-stop-daemon --start --quiet --chuid $RUNAS --pidfile $PIDSPATH/$PIDFILE --exec $DAEMON \
                -- -c $NGINX_CONF_FILE
                setFilePerms
                log_end_msg $SCRIPT_OK
        fi
}
 
stop() {
	log_daemon_msg "Stopping $DESCRIPTION"
 
	isRunning
	isAlive=$?
        if [ "${isAlive}" -eq $TRUE ]; then
                start-stop-daemon --stop --quiet --pidfile $PIDSPATH/$PIDFILE
 
		wait_for_pid 'removed' $PIDSPATH/$PIDFILE
 
                if [ -n "$try" ] ; then
                        log_end_msg $SCRIPT_ERROR
                else
                        removePIDFile
	                log_end_msg $SCRIPT_OK
                fi
 
        else
                log_end_msg $SCRIPT_ERROR
        fi
}
 
reload() {
	configtest || return $?
 
	log_daemon_msg "Reloading (via HUP) $DESCRIPTION"
 
        isRunning
        if [ $? -eq $TRUE ]; then
		`killall -HUP $PS` #to be safe
 
                log_end_msg $SCRIPT_OK
        else
                log_end_msg $SCRIPT_ERROR
        fi
}
 
quietupgrade() {
	log_daemon_msg "Peforming Quiet Upgrade $DESCRIPTION"
 
        isRunning
        isAlive=$?
        if [ "${isAlive}" -eq $TRUE ]; then
		kill -USR2 `cat $PIDSPATH/$PIDFILE`
		kill -WINCH `cat $PIDSPATH/$PIDFILE.oldbin`
 
		isRunning
		isAlive=$?
		if [ "${isAlive}" -eq $TRUE ]; then
			kill -QUIT `cat $PIDSPATH/$PIDFILE.oldbin`
			wait_for_pid 'removed' $PIDSPATH/$PIDFILE.oldbin
                        removePIDFile $PIDSPATH/$PIDFILE.oldbin
 
			log_end_msg $SCRIPT_OK
		else
			log_end_msg $SCRIPT_ERROR
 
			log_daemon_msg "ERROR! Reverting back to original $DESCRIPTION"
 
			kill -HUP `cat $PIDSPATH/$PIDFILE`
			kill -TERM `cat $PIDSPATH/$PIDFILE.oldbin`
			kill -QUIT `cat $PIDSPATH/$PIDFILE.oldbin`
 
			wait_for_pid 'removed' $PIDSPATH/$PIDFILE.oldbin
                        removePIDFile $PIDSPATH/$PIDFILE.oldbin
 
			log_end_msg $SCRIPT_ok
		fi
        else
                log_end_msg $SCRIPT_ERROR
        fi
}
 
terminate() {
        log_daemon_msg "Force terminating (via KILL) $DESCRIPTION"
 
	PIDS=`pidof $PS` || true
 
	[ -e $PIDSPATH/$PIDFILE ] && PIDS2=`cat $PIDSPATH/$PIDFILE`
 
	for i in $PIDS; do
		if [ "$i" = "$PIDS2" ]; then
	        	kill $i
                        wait_for_pid 'removed' $PIDSPATH/$PIDFILE
			removePIDFile
		fi
	done
 
	log_end_msg $SCRIPT_OK
}
 
destroy() {
	log_daemon_msg "Force terminating and may include self (via KILLALL) $DESCRIPTION"
	killall $PS -q >> /dev/null 2>&1
	log_end_msg $SCRIPT_OK
}
 
pidof_daemon() {
    PIDS=`pidof $PS` || true
 
    [ -e $PIDSPATH/$PIDFILE ] && PIDS2=`cat $PIDSPATH/$PIDFILE`
 
    for i in $PIDS; do
        if [ "$i" = "$PIDS2" ]; then
            return 1
        fi
    done
    return 0
}
 
case "$1" in
  start)
	start
        ;;
  stop)
	stop
        ;;
  restart|force-reload)
	stop
	sleep 1
	start
        ;;
  reload)
	$1
	;;
  status)
	status
	;;
  configtest)
        $1
        ;;
  quietupgrade)
	$1
	;;
  terminate)
	$1
	;;
  destroy)
	$1
	;;
  *)
	FULLPATH=/etc/init.d/$PS
	echo "Usage: $FULLPATH {start|stop|restart|force-reload|status|configtest|quietupgrade|terminate|destroy}"
	echo "       The 'destroy' command should only be used as a last resort." 
	exit 1
	;;
esac
 
exit 0

Guarda el archivo, presionando Ctrl+X y responde Y, luego presiona enter para grabar el archivo. Para poder ejecutar este archivo debes dar permisos de ejecución.

chmod +x /etc/init.d/nginx

Ahora solo hace falta que compruebes que todo funciona correcto, ve como hacerlo en la siguiente página.

This entry was posted in Ubuntu and tagged , , , . Bookmark the permalink.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *


*


Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.