Apache advanced主题tutorial

Learningadvancedfunctions and 企业级application

查看tutoriallist

Apache advanced主题

Apache HTTP Server is a functions强 big , flexible Webserver, providing了许 many advancedfunctions, 适用于企业级application场景. 本文将详细介绍Apache advancedfunctions and 企业级application, includinghigh availability性configuration, clusterdeployment, containers集成, APIgateway, in 容managementsystem集成etc., helping您构建一个 stable , high 效, security 企业级Webservice平台.

Apache high availability性configuration

high availability性(HA) is 企业级application 关键要求, 它确保service in 各种failurecircumstances under 仍能正常run. Apacheproviding了 many 种implementationhigh availability性 solutions:

1. 基于硬件 load balancing

硬件load balancing器 is implementationhigh availability性 最 reliable solutions之一, such asF5, Citrix NetScaleretc.. 它们providing了advanced load balancing, healthycheck and failure转移functions.

2. 基于软件 load balancing

# usingHAProxyserving asload balancing器 # installationHAProxy sudo apt install haproxy # configurationHAProxy sudo nano /etc/haproxy/haproxy.cfg # 添加以 under in 容 frontend apache_frontend bind *:80 mode http default_backend apache_backend backend apache_backend mode http balance roundrobin option httpchk GET /health.html server apache1 192.168.1.10:80 check server apache2 192.168.1.11:80 check # 重启HAProxy sudo systemctl restart haproxy # creationhealthycheckfile for server in 192.168.1.10 192.168.1.11; do ssh $server "echo 'OK' > /var/www/html/health.html" done

3. 基于Apache load balancing

# 启用load balancingmodule sudo a2enmod proxy proxy_http proxy_balancer lbmethod_byrequests # configurationload balancing sudo nano /etc/apache2/sites-available/loadbalancer.conf # 添加以 under in 容 <VirtualHost *:80> ServerName example.com <Proxy balancer://mycluster> BalancerMember http://192.168.1.10:80 BalancerMember http://192.168.1.11:80 ProxySet lbmethod=byrequests </Proxy> ProxyPass / balancer://mycluster/ ProxyPassReverse / balancer://mycluster/ # 启用status页面 <Location /balancer-manager> Setprocessingr balancer-manager Require ip 192.168.1.0/24 </Location> </VirtualHost> # 启用站点 sudo a2ensite loadbalancer # 重启Apache sudo systemctl restart apache2

4. 基于Keepalived high availability

# installationKeepalived sudo apt install keepalived # configurationKeepalived sudo nano /etc/keepalived/keepalived.conf # 添加以 under in 容 (主server) global_defs { router_id LVS_DEVEL } vrrp_script chk_http_port { script "/usr/local/bin/check_http.sh" interval 2 weight 2 } vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 101 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.1.200 } track_script { chk_http_port } } # creationhealthycheck脚本 sudo nano /usr/local/bin/check_http.sh # 添加以 under in 容 #!/bin/bash if [ $(ps aux | grep apache2 | grep -v grep | wc -l) -eq 0 ]; then systemctl start apache2 sleep 2 if [ $(ps aux | grep apache2 | grep -v grep | wc -l) -eq 0 ]; then systemctl stop keepalived fi fi # 设置脚本permission sudo chmod +x /usr/local/bin/check_http.sh # 重启Keepalived sudo systemctl restart keepalived

Apache clusterdeployment

Apacheclusterdeployment is 企业级application commonrequirements, 它可以improvingservice reliability and scale性.

1. 基于共享store cluster

usingNFS, GlusterFS or Cephetc.共享storesolution, 确保所 has Apacheserver访问相同 网站 in 容.

# installationNFSserver ( in storeserver on ) sudo apt install nfs-kernel-server # creation共享Table of Contents sudo mkdir -p /srv/nfs/www # configurationNFS sudo nano /etc/exports # 添加以 under in 容 /srv/nfs/www 192.168.1.0/24(rw,sync,no_root_squash,no_subtree_check) # export共享Table of Contents sudo exportfs -a # 重启NFSservice sudo systemctl restart nfs-kernel-server # in Apacheserver on 挂载NFS sudo apt install nfs-common sudo mkdir -p /var/www/html sudo mount 192.168.1.5:/srv/nfs/www /var/www/html # 添加 to fstabimplementation自动挂载 sudo nano /etc/fstab # 添加以 under in 容 192.168.1.5:/srv/nfs/www /var/www/html nfs defaults 0 0

2. 基于datalibrary session共享

for 于usingsession application, 需要implementationsession共享, 确保user in 不同 Apacheserver之间切换时session不loss.

# installationPHP and MySQL (such as果未installation) sudo apt install php php-mysql mysql-server # creationsessiondatalibrary mysql -u root -p CREATE DATABASE session_db; CREATE USER 'session_user'@'%' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON session_db.* TO 'session_user'@'%'; FLUSH PRIVILEGES; # creationsession表 USE session_db; CREATE TABLE sessions ( id VARCHAR(32) NOT NULL, access INT(10) UNSIGNED, data TEXT, PRIMARY KEY (id) ); # configurationPHPusingdatalibrarystoresession sudo nano /etc/php/7.4/apache2/php.ini # modify以 under parameter session.save_handler = user session.save_path = "mysql:host=localhost;dbname=session_db;port=3306" # 重启Apache sudo systemctl restart apache2

Apache containers集成

containerstechniquessuch asDocker and Kubernetes已经成 for 现代applicationdeployment 标准, Apache可以很 good 地集成 to containersenvironmentin.

1. Docker deployment Apache

# creationDockerfile FROM httpd:2.4 # copyconfigurationfile COPY httpd.conf /usr/local/apache2/conf/httpd.conf COPY extra/httpd-vhosts.conf /usr/local/apache2/conf/extra/httpd-vhosts.conf # copy网站 in 容 COPY htdocs/ /usr/local/apache2/htdocs/ # 暴露端口 EXPOSE 80 443 # 构建镜像 docker build -t apache-custom . # runcontainers docker run -d -p 80:80 -p 443:443 --name apache-server apache-custom # usingdocker-compose # creationdocker-compose.yml version: '3' services: apache: build: . ports: - "80:80" - "443:443" volumes: - ./htdocs:/usr/local/apache2/htdocs - ./logs:/usr/local/apache2/logs restart: always # 启动service docker-compose up -d

2. Kubernetes deployment Apache

# creationdeploymentmentconfiguration apiVersion: apps/v1 kind: deploymentment metadata: name: apache-deployment labels: app: apache spec: replicas: 3 selector: matchLabels: app: apache template: metadata: labels: app: apache spec: containers: - name: apache image: httpd:2.4 ports: - containerPort: 80 volumeMounts: - name: apache-config mountPath: /usr/local/apache2/conf/httpd.conf subPath: httpd.conf - name: apache-vhosts mountPath: /usr/local/apache2/conf/extra/httpd-vhosts.conf subPath: httpd-vhosts.conf - name: apache-htdocs mountPath: /usr/local/apache2/htdocs volumes: - name: apache-config configMap: name: apache-config - name: apache-vhosts configMap: name: apache-vhosts - name: apache-htdocs persistentVolumeClaim: claimName: apache-htdocs-pvc # creationServiceconfiguration apiVersion: v1 kind: Service metadata: name: apache-service spec: selector: app: apache ports: - port: 80 targetPort: 80 type: LoadBalancer # applicationconfiguration kubectl apply -f apache-deployment.yaml kubectl apply -f apache-service.yaml

Apache serving as API gateway

Apache可以configuration for APIgateway, processingAPIrequest routing, authentication, 限流etc.functions.

# 启用必要 module sudo a2enmod proxy proxy_http proxy_balancer lbmethod_byrequests headers rewrite # configurationAPIgateway sudo nano /etc/apache2/sites-available/api-gateway.conf # 添加以 under in 容 <VirtualHost *:80> ServerName api.example.com # configurationCORS Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header set Access-Control-Allow-Headers "Content-Type, Authorization" # APIrouting <Location /api/users> ProxyPass http://backend1:8080/users ProxyPassReverse http://backend1:8080/users # authenticationconfiguration AuthType Bearer AuthName "API Access" AuthBearerProvider file AuthBearerFile /etc/apache2/auth/api_tokens Require valid-user </Location> <Location /api/products> ProxyPass http://backend2:8080/products ProxyPassReverse http://backend2:8080/products # 限流configuration LimitRequestRate 10 5 </Location> <Location /api/orders> ProxyPass http://backend3:8080/orders ProxyPassReverse http://backend3:8080/orders </Location> </VirtualHost> # creationAPItokenfile sudo htpasswd -c -B -b /etc/apache2/auth/api_tokens user1 token123 # 启用站点 sudo a2ensite api-gateway # 重启Apache sudo systemctl restart apache2

Apache and in 容managementsystem集成

Apache is 许 many in 容managementsystem(CMS) 首选Webserver, such asWordPress, Drupal, Joomlaetc..

1. WordPress optimizationconfiguration

# configurationWordPress虚拟主机 sudo nano /etc/apache2/sites-available/wordpress.conf # 添加以 under in 容 <VirtualHost *:80> ServerName wordpress.example.com DocumentRoot /var/www/wordpress <Directory /var/www/wordpress> Options FollowSymLinks AllowOverride All Require all granted </Directory> # 启用压缩 <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json </IfModule> # 启用cache <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule> # logconfiguration ErrorLog ${APACHE_LOG_DIR}/wordpress_error.log CustomLog ${APACHE_LOG_DIR}/wordpress_access.log combined </VirtualHost> # 启用必要 module sudo a2enmod rewrite deflate expires headers # 启用站点 sudo a2ensite wordpress # 重启Apache sudo systemctl restart apache2

2. Drupal optimizationconfiguration

# configurationDrupal虚拟主机 sudo nano /etc/apache2/sites-available/drupal.conf # 添加以 under in 容 <VirtualHost *:80> ServerName drupal.example.com DocumentRoot /var/www/drupal <Directory /var/www/drupal> Options FollowSymLinks AllowOverride All Require all granted </Directory> # memory限制 php_value memory_limit 512M # on 传file big small 限制 php_value upload_max_filesize 64M php_value post_max_size 64M # 执行时间限制 php_value max_execution_time 300 # logconfiguration ErrorLog ${APACHE_LOG_DIR}/drupal_error.log CustomLog ${APACHE_LOG_DIR}/drupal_access.log combined </VirtualHost> # 启用必要 module sudo a2enmod rewrite # 启用站点 sudo a2ensite drupal # 重启Apache sudo systemctl restart apache2

Apache monitor and management

企业级application需要完善 monitor and managementmechanism, 以确保service stable 性 and performance.

1. using Apache 自带 statusmodule

# 启用statusmodule sudo a2enmod status # configurationstatus页面 sudo nano /etc/apache2/mods-enabled/status.conf # modify以 under in 容 <Location /server-status> Setprocessingr server-status Require ip 192.168.1.0/24 </Location> # 重启Apache sudo systemctl restart apache2 # 访问status页面 # http://server-ip/server-status

2. using Prometheus and Grafana monitor

# installationApache Exporter sudo apt install wget wget https://github.com/Lusitaniae/apache_exporter/releases/download/v0.11.0/apache_exporter-0.11.0.linux-amd64.tar.gz tar -xzf apache_exporter-0.11.0.linux-amd64.tar.gz cd apache_exporter-0.11.0.linux-amd64 sudo cp apache_exporter /usr/local/bin/ # creationsystemservice sudo nano /etc/systemd/system/apache_exporter.service # 添加以 under in 容 [Unit] Description=Apache Exporter After=network.target [Service] Type=simple User=nobody ExecStart=/usr/local/bin/apache_exporter [Install] WantedBy=multi-user.target # 启动service sudo systemctl daemon-reload sudo systemctl enable apache_exporter sudo systemctl start apache_exporter # configurationPrometheus sudo nano /etc/prometheus/prometheus.yml # 添加以 under in 容 scrape_configs: - job_name: 'apache' static_configs: - targets: ['localhost:9117'] # 重启Prometheus sudo systemctl restart prometheus # in GrafanainimportApache仪表板 # 仪表板ID: 3894

Apache 企业级security加固

企业级application for security性要求很 high , 需要采取一系列security加固措施:

1. advancedsecurityconfiguration

# configurationsecurity头 sudo nano /etc/apache2/conf-available/security-headers.conf # 添加以 under in 容 Header set X-Content-Type-Options "nosniff" Header set X-Frame-Options "SAMEORIGIN" Header set X-XSS-Protection "1; mode=block" Header set Strict-Transport-Security "max-age=31536000; includeSubDomains" Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'self';" # 启用security头configuration sudo a2enconf security-headers # 禁用不必要 module sudo a2dismod autoindex status info # 限制request big small sudo nano /etc/apache2/conf-available/request-limits.conf # 添加以 under in 容 LimitRequestBody 10485760 # 10MB LimitRequestFields 50 LimitRequestFieldSize 8190 # 启用request限制configuration sudo a2enconf request-limits # 重启Apache sudo systemctl restart apache2

2. using ModSecurity serving as Web application防火墙

# installationModSecurity sudo apt install libapache2-mod-security2 # configurationModSecurity sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf sudo nano /etc/modsecurity/modsecurity.conf # modify以 under parameter SecRuleEngine On # installationOWASPcore规则集 sudo apt install git sudo git clone https://github.com/coreruleset/coreruleset.git /etc/modsecurity/crs sudo cp /etc/modsecurity/crs/crs-setup.conf.example /etc/modsecurity/crs/crs-setup.conf # configurationApacheusingModSecurity sudo nano /etc/apache2/mods-enabled/security2.conf # 添加以 under in 容 <IfModule security2_module> SecDataDir /var/cache/modsecurity Include /etc/modsecurity/modsecurity.conf Include /etc/modsecurity/crs/crs-setup.conf Include /etc/modsecurity/crs/rules/*.conf </IfModule> # 重启Apache sudo systemctl restart apache2

Apache performance调优best practices

企业级application需要 high performance Webserver, 以 under is 一些performance调优 best practices:

  • 选择合适 MPMmodule: 根据server硬件 and traffic特点选择合适 MPMmodule (prefork, worker or event) .
  • optimizationMPMconfiguration: 根据servermemory and CPUcore数调整MPMparameter.
  • 启用压缩: usingmod_deflate or mod_brotli压缩静态 and 动态 in 容.
  • 启用cache: usingmod_cache and mod_disk_cachecache静态 in 容.
  • using in 容分发network(CDN): 将静态 in 容分发 to 全球各地 CDNnode.
  • optimizationSSLconfiguration: using现代 SSL/TLSprotocol and password套件, 启用OCSP Stapling.
  • usingHTTP/2: 启用HTTP/2protocol, improvingconcurrent连接performance.
  • optimizationdatalibrary连接: using连接池reducingdatalibrary连接开销.
  • usingmemorycache: such asMemcached or Rediscache频繁访问 data.
  • 定期monitor and analysis: usingmonitortool定期analysisserverperformance, 及时调整configuration.

performance调优建议

performance调优 is a 持续 过程, 需要根据practicaltraffic and application特点continuously调整. 建议 from 以 under 几个方面入手:

  • monitorserverresourceusingcircumstances (CPU, memory, diskI/O, network)
  • analysis访问log, Understandtraffic模式 and 瓶颈
  • using压测tool (such asApache Bench, JMeter) testserverperformance
  • from small 规模调整开始, 逐步optimization
  • 记录每次调整 效果, 便于rollback

实践case: 企业级Apacheclusterdeployment

步骤1: deploymentApacheservercluster

# in 所 has server on installationApache sudo apt update sudo apt install apache2 # configurationApache sudo nano /etc/apache2/apache2.conf # modify以 under parameter KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 # configurationMPM sudo nano /etc/apache2/mods-enabled/mpm_prefork.conf # modify以 under parameter <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule>

步骤2: configurationload balancing

# installationHAProxy sudo apt install haproxy # configurationHAProxy sudo nano /etc/haproxy/haproxy.cfg # 添加以 under in 容 frontend apache_frontend bind *:80 mode http default_backend apache_backend backend apache_backend mode http balance roundrobin option httpchk GET /health.html server apache1 192.168.1.10:80 check server apache2 192.168.1.11:80 check # 重启HAProxy sudo systemctl restart haproxy

步骤3: configuration共享store

# installationNFSserver sudo apt install nfs-kernel-server # creation共享Table of Contents sudo mkdir -p /srv/nfs/www # configurationNFS sudo nano /etc/exports # 添加以 under in 容 /srv/nfs/www 192.168.1.0/24(rw,sync,no_root_squash,no_subtree_check) # export共享Table of Contents sudo exportfs -a # 重启NFSservice sudo systemctl restart nfs-kernel-server # in Apacheserver on 挂载NFS sudo apt install nfs-common sudo mkdir -p /var/www/html sudo mount 192.168.1.5:/srv/nfs/www /var/www/html # 添加 to fstabimplementation自动挂载 sudo nano /etc/fstab # 添加以 under in 容 192.168.1.5:/srv/nfs/www /var/www/html nfs defaults 0 0

步骤4: configurationSSLcertificate

# installationLet's Encryptcertificate sudo apt install certbot python3-certbot-apache # 获取certificate sudo certbot --apache -d example.com # configurationHAProxyusingSSL sudo nano /etc/haproxy/haproxy.cfg # 添加以 under in 容 frontend apache_frontend_ssl bind *:443 ssl crt /etc/letsencrypt/live/example.com/fullchain.pem key /etc/letsencrypt/live/example.com/privkey.pem mode http default_backend apache_backend # 重启HAProxy sudo systemctl restart haproxy

步骤5: configurationmonitor

# installationApache Exporter sudo apt install wget wget https://github.com/Lusitaniae/apache_exporter/releases/download/v0.11.0/apache_exporter-0.11.0.linux-amd64.tar.gz tar -xzf apache_exporter-0.11.0.linux-amd64.tar.gz cd apache_exporter-0.11.0.linux-amd64 sudo cp apache_exporter /usr/local/bin/ # creationsystemservice sudo nano /etc/systemd/system/apache_exporter.service # 添加以 under in 容 [Unit] Description=Apache Exporter After=network.target [Service] Type=simple User=nobody ExecStart=/usr/local/bin/apache_exporter [Install] WantedBy=multi-user.target # 启动service sudo systemctl daemon-reload sudo systemctl enable apache_exporter sudo systemctl start apache_exporter

互动练习

练习1: configurationApachehigh availability性cluster

configuration一个high availability性 Apachecluster, 要求:

  • usingHAProxyserving asload balancing器
  • deployment至 few 2个Apacheservernode
  • configurationhealthycheck and failure转移
  • testfailure转移functions

练习2: DockerdeploymentApache

usingDockerdeploymentApache, 要求:

  • creation自定义Docker镜像
  • configuration虚拟主机
  • 挂载卷implementationdata持久化
  • usingdocker-composemanagementservice

练习3: configurationApache APIgateway

configurationApacheserving asAPIgateway, 要求:

  • configurationAPIrouting
  • implementationauthenticationfunctions
  • configurationCORS
  • testAPI访问

练习4: 企业级security加固

for Apachefor企业级security加固, 要求:

  • configurationsecurity头
  • installation并configurationModSecurity
  • 启用OWASPcore规则集
  • testsecurityconfiguration