Configurar proxy inverso en Linux

Guía detallada para configurar un proxy inverso con Apache y Tomcat usando mod_jk y AJP en entornos productivos, con balanceo, sesiones sticky, failover y buenas prácticas de seguridad.

26 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: este artículo explica paso a paso cómo configurar un proxy inverso en Linux usando Apache y Tomcat con mod_jk traducido y adaptado para entornos productivos. Incluye requisitos previos, creación de un sitio virtual, activación de AJP en Tomcat, configuración de mod_jk, balanceo de carga, sesiones sticky y pruebas de fail over. También presentamos a Q2BSTUDIO, empresa de desarrollo de software a medida, inteligencia artificial y ciberseguridad, que ofrece soluciones completas para desplegar infraestructuras web seguras y escalables.

Requisitos previos: tener un clúster Tomcat instalado y configurado. Definir en ~/.bashrc variables de entorno como TOMCAT1_HOME TOMCAT2_HOME y MYSITE_HOME. Verificar que Apache está instalado con systemctl status apache2. Q2BSTUDIO puede ayudar con la puesta en marcha y el diseño de la arquitectura, tanto si buscas software a medida como despliegues en la nube.

Crear un nuevo sitio: en ~/.bashrc añadir export TOMCAT1_HOME=/ruta/a/tomcat1 export TOMCAT2_HOME=/ruta/a/tomcat2 export MYSITE_HOME=/var/sites/mysite y ejecutar source ~/.bashrc. También declarar MYSITE_HOME en /etc/apache2/envvars. Crear las carpetas de configuración y www mkdir -p $MYSITE_HOME/conf mkdir -p $MYSITE_HOME/www/html y un index.html básico en $MYSITE_HOME/www/html. Copiar la configuración por defecto de Apache cp /etc/apache2/sites-available/000-default.conf $MYSITE_HOME/conf/localhost.conf y editar DocumentRoot y Directory para apuntar a ${MYSITE_HOME}/www/html. Habilitar el sitio creando un enlace simbólico ln -s $MYSITE_HOME/conf/localhost.conf /etc/apache2/sites-available/local-localhost.conf y ejecutar a2ensite local-localhost seguido de systemctl reload apache2. Reiniciar Apache con systemctl stop apache2 systemctl start apache2 y comprobar con curl https://localhost que la página responde.

Elegir entre mod_proxy y mod_jk: ambas opciones permiten que Apache actúe como proxy inverso hacia Tomcat. En este artículo usamos mod_jk y el protocolo AJP por su eficiencia en entornos con Tomcat. Si tu objetivo es integrar con servicios en la nube, podemos desplegar soluciones compatibles con servicios cloud aws y azure para alta disponibilidad y escalado automático.

Habilitar AJP en Tomcat: editar conf/server.xml de cada Tomcat y activar el conector AJP. Ejemplo para tomcat1 mostrar como texto: <Connector protocol=AJP/1.3 address=localhost port=8009 redirectPort=8443 maxParameterCount=1000 secretRequired=false /> para tomcat2 usar un puerto distinto como 9009 y address=127.0.0.1 si procede. Reiniciar ambos Tomcat y verificar con netstat que los puertos 8009 y 9009 están a la escucha.

Configurar mod_jk: copiar jk.conf y jk.load por defecto desde /etc/apache2/mods-available a $MYSITE_HOME/conf. Crear $MYSITE_HOME/conf/workers.properties con la lista y las propiedades de cada worker por ejemplo worker.list=worker1, worker2, lb worker.worker1.type=ajp13 worker.worker1.host=localhost worker.worker1.port=8009 worker.worker2.type=ajp13 worker.worker2.host=localhost worker.worker2.port=9009 worker.lb.type=lb worker.lb.balance_workers=worker1, worker2 Crear $MYSITE_HOME/conf/uriworkermap.properties para mapear rutas como /examples/*=lb e incluir en $MYSITE_HOME/conf/jk.conf las directivas JkWorkersFile ${MYSITE_HOME}/conf/workers.properties y JkMountFile ${MYSITE_HOME}/conf/uriworkermap.properties.

Activar la configuración personalizada: crear enlaces simbólicos ln -s $MYSITE_HOME/conf/jk.conf /etc/apache2/mods-available/local-jk.conf ln -s $MYSITE_HOME/conf/jk.load /etc/apache2/mods-available/local-jk.load Deshabilitar el módulo jk por defecto a2dismod jk y habilitar el local-jk a2enmod local-jk. Recargar Apache con systemctl reload apache2. Ahora las peticiones a rutas mapeadas deben ser reenviadas a Tomcat y responder correctamente al consultar con curl https://localhost/examples/.

Pruebas y validación: comprobar balanceo de carga alternando peticiones a un servlet de sesión. Para identificar cada nodo es útil modificar en cada Tomcat un recurso de textos con un sufijo 1 o 2 y así ver a qué instancia llega cada petición. Para sesiones sticky configurar en conf/server.xml de cada Tomcat el atributo jvmRoute en el elemento Engine por ejemplo <Engine jvmRoute=worker1 name=Catalina> y en el otro nodo jvmRoute=worker2. Conservar la cookie JSESSIONID entre peticiones permite validar que las solicitudes de la misma sesión se mantienen en el mismo nodo.

Fail over: probar deteniendo un Tomcat que estaba sirviendo una sesión y volver a realizar la petición con la cookie JSESSIONID original. El balanceador debe reenviar la sesión al otro nodo y preservar el identificador de sesión cuando esté disponible la réplica o el mecanismo de sesión distributiva esté configurado. Q2BSTUDIO puede ayudar a diseñar estrategias de replicación de sesión y persistencia para garantizar continuidad de servicio.

Buenas prácticas y seguridad: asegurar los conectores AJP limitando address a interfaces internas y configurar secret cuando el entorno lo permita. Restringir permisos de archivos y emplear cortafuegos para minimizar la exposición. Considerar el uso de certificados TLS para proteger el tráfico externo y aplicar políticas de ciberseguridad y pentesting periódicas. Si necesitas auditoría y pruebas de seguridad, visita nuestra página de servicios en ciberseguridad ciber seguridad y pentesting para más información.

Servicios complementarios de Q2BSTUDIO: como empresa de desarrollo y consultoría ofrecemos soluciones integrales incluyendo desarrollo de aplicaciones a medida, integración con servicios cloud, soluciones de inteligencia artificial y agentes IA para empresas, servicios de inteligencia de negocio y dashboards con power bi, y auditorías de ciberseguridad. Palabras clave relevantes que trabajamos para mejorar posicionamiento y resultados de negocio aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

Resumen y siguiente paso: revisar las configuraciones, hacer pruebas de carga y fallos, y documentar los procedimientos de recuperación. Si quieres que Q2BSTUDIO implemente la solución, optimice el balanceo, garantice sesiones sticky y configure monitorización y alertas, contacta para una consultoría a medida. Podemos ofrecer soporte tanto en arquitectura como en desarrollo y seguridad para que tu proxy inverso sea robusto y escalable.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat