简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:为庆祝网站一周年,将在5.1日与5.2日开放注册,具体信息请见后续详细公告
04-22 00:04
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

Alpine Linux与Apache Web服务器部署完全手册详解轻量级系统与强大Web服务器的完美结合从基础环境搭建到服务配置再到安全优化与性能调优的全方位实战教程

SunJu_FaceMall

3万

主题

1174

科技点

3万

积分

白金月票

碾压王

积分
32796

立华奏

发表于 2025-8-23 22:50:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

Alpine Linux是一款基于 musl libc 和 BusyBox 的轻量级 Linux 发行版,以其小巧、安全和高效率而著称。它的镜像大小通常只有几MB,非常适合容器化环境和资源受限的服务器。而 Apache Web 服务器(也称为 HTTPD)则是全球最流行的 Web 服务器软件之一,以其稳定性、灵活性和丰富的功能模块而闻名。

将 Alpine Linux 与 Apache Web 服务器相结合,可以构建一个既轻量又功能强大的 Web 服务环境。这种组合特别适合追求高效率、高安全性的现代 Web 应用部署场景。本教程将带领读者从零开始,逐步搭建一个基于 Alpine Linux 的 Apache Web 服务器,并对其进行全面的安全优化和性能调优。

1. Alpine Linux 基础环境搭建

1.1 Alpine Linux 安装

Alpine Linux 提供了多种安装方式,包括标准安装、Docker 容器以及云镜像等。本节将介绍标准安装过程。

首先,从 Alpine Linux 官方网站(https://alpinelinux.org/downloads/)下载最新的标准ISO 镜像。根据系统架构选择合适的版本(通常为 x86_64)。

使用以下命令将 ISO 镜像写入 USB 设备(以 Linux 系统为例):
  1. # 确定 USB 设备名称(如 /dev/sdb)
  2. lsblk
  3. # 卸载设备(如果已挂载)
  4. sudo umount /dev/sdb*
  5. # 将 ISO 写入 USB 设备
  6. sudo dd if=alpine-standard-3.19.0-x86_64.iso of=/dev/sdb bs=4M status=progress
复制代码

1. 从 USB 设备启动计算机,选择 “Boot Alpine Linux” 选项。
2. 登录系统(默认用户为 root,无密码)。
3. 运行安装向导:
  1. # 启动安装向导
  2. setup-alpine
复制代码

安装过程中,系统会提示以下信息:

• 键盘布局(默认为 us)
• 主机名(例如:webserver)
• 网络接口配置(可选择 DHCP 或静态 IP)
• 密码设置
• 时区配置
• 代理设置(如有)
• NTP 客户端(chrony)配置
• 镜像源(可选择默认或自定义)
• SSH 服务器(OpenSSH)配置
• 磁盘配置(选择 sys 模式将系统安装到磁盘)

安装完成后,更新系统并安装必要的软件包:
  1. # 更新软件包索引
  2. apk update
  3. # 升级已安装的软件包
  4. apk upgrade
  5. # 安装基础工具包
  6. apk add bash vim curl wget git sudo
复制代码

1.2 系统基础配置

Alpine Linux 使用ifupdown-ng作为网络管理工具。网络配置文件位于/etc/network/interfaces。

静态 IP 配置示例:
  1. # 编辑网络配置文件
  2. vi /etc/network/interfaces
  3. # 添加以下内容(根据实际情况修改)
  4. auto lo
  5. iface lo inet loopback
  6. auto eth0
  7. iface eth0 inet static
  8.     address 192.168.1.100
  9.     netmask 255.255.255.0
  10.     gateway 192.168.1.1
  11.     dns-nameservers 8.8.8.8 8.8.4.4
复制代码

重启网络服务:
  1. # 重启网络服务
  2. service networking restart
复制代码

为了提高系统安全性,建议添加普通用户并配置 sudo 权限:
  1. # 添加新用户(例如:webadmin)
  2. adduser webadmin
  3. # 安装 sudo 软件包(如果尚未安装)
  4. apk add sudo
  5. # 配置 sudo 权限
  6. visudo
  7. # 添加以下行,允许 webadmin 用户使用 sudo
  8. webadmin ALL=(ALL) ALL
复制代码

为了远程管理服务器,需要配置 SSH 服务:
  1. # 安装 OpenSSH 服务器(如果尚未安装)
  2. apk add openssh-server
  3. # 启动 SSH 服务
  4. service sshd start
  5. # 设置 SSH 服务开机自启
  6. rc-update add sshd default
  7. # 编辑 SSH 配置文件
  8. vi /etc/ssh/sshd_config
  9. # 修改以下配置以提高安全性
  10. PermitRootLogin no
  11. PasswordAuthentication no
  12. Port 2222  # 更改默认端口
复制代码

重启 SSH 服务:
  1. service sshd restart
复制代码

Alpine Linux 默认使用iptables作为防火墙工具。以下是一个基本配置示例:
  1. # 安装 iptables
  2. apk add iptables ip6tables
  3. # 创建 IPv4 防火墙规则
  4. vi /etc/iptables/rules.v4
  5. # 添加以下内容
  6. *filter
  7. :INPUT DROP [0:0]
  8. :FORWARD DROP [0:0]
  9. :OUTPUT ACCEPT [0:0]
  10. # 允许本地回环
  11. -A INPUT -i lo -j ACCEPT
  12. # 允许已建立的连接
  13. -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  14. # 允许 SSH(端口已更改为 2222)
  15. -A INPUT -p tcp --dport 2222 -j ACCEPT
  16. # 允许 HTTP 和 HTTPS
  17. -A INPUT -p tcp --dport 80 -j ACCEPT
  18. -A INPUT -p tcp --dport 443 -j ACCEPT
  19. # 允许 ICMP
  20. -A INPUT -p icmp -j ACCEPT
  21. COMMIT
  22. # 创建 IPv6 防火墙规则
  23. vi /etc/iptables/rules.v6
  24. # 添加与 IPv4 类似的规则,但针对 IPv6
  25. *filter
  26. :INPUT DROP [0:0]
  27. :FORWARD DROP [0:0]
  28. :OUTPUT ACCEPT [0:0]
  29. -A INPUT -i lo -j ACCEPT
  30. -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  31. -A INPUT -p tcp --dport 2222 -j ACCEPT
  32. -A INPUT -p tcp --dport 80 -j ACCEPT
  33. -A INPUT -p tcp --dport 443 -j ACCEPT
  34. -A INPUT -p ipv6-icmp -j ACCEPT
  35. COMMIT
  36. # 创建 iptables 启动脚本
  37. vi /etc/local.d/iptables.start
  38. # 添加以下内容
  39. #!/bin/sh
  40. iptables-restore < /etc/iptables/rules.v4
  41. ip6tables-restore < /etc/iptables/rules.v6
  42. # 设置脚本可执行权限
  43. chmod +x /etc/local.d/iptables.start
  44. # 添加到本地服务
  45. rc-update add local default
  46. # 启动防火墙规则
  47. /etc/local.d/iptables.start
复制代码

至此,Alpine Linux 的基础环境已经搭建完成,接下来我们将安装和配置 Apache Web 服务器。

2. Apache Web 服务器安装与基础配置

2.1 安装 Apache Web 服务器

在 Alpine Linux 上,Apache Web 服务器通过apache2软件包提供:
  1. # 安装 Apache Web 服务器
  2. apk add apache2
  3. # 启动 Apache 服务
  4. service apache2 start
  5. # 设置 Apache 服务开机自启
  6. rc-update add apache2 default
复制代码

2.2 Apache 基础配置

Apache 的主配置文件位于/etc/apache2/httpd.conf。让我们先备份原始配置文件,然后进行必要的修改:
  1. # 备份原始配置文件
  2. cp /etc/apache2/httpd.conf /etc/apache2/httpd.conf.bak
  3. # 编辑配置文件
  4. vi /etc/apache2/httpd.conf
复制代码

以下是一些重要的基础配置项:
  1. # 服务器根目录
  2. ServerRoot "/var/www"
  3. # 监听端口(默认为 80)
  4. Listen 80
  5. # 服务器管理员邮箱
  6. ServerAdmin admin@example.com
  7. # 服务器主机名
  8. ServerName webserver.example.com:80
  9. # 默认文档根目录
  10. DocumentRoot "/var/www/localhost/htdocs"
  11. # 目录访问控制
  12. <Directory "/var/www/localhost/htdocs">
  13.     Options Indexes FollowSymLinks
  14.     AllowOverride None
  15.     Require all granted
  16. </Directory>
  17. # 错误日志
  18. ErrorLog "/var/log/apache2/error.log"
  19. # 访问日志
  20. CustomLog "/var/log/apache2/access.log" common
复制代码

2.3 测试 Apache 服务器

配置完成后,重启 Apache 服务并测试:
  1. # 重启 Apache 服务
  2. service apache2 restart
  3. # 创建测试页面
  4. echo "<html><body><h1>Apache on Alpine Linux</h1><p>It works!</p></body></html>" > /var/www/localhost/htdocs/index.html
  5. # 检查服务状态
  6. service apache2 status
复制代码

现在,可以通过浏览器访问服务器的 IP 地址,应该能看到 “It works!” 页面。

2.4 虚拟主机配置

虚拟主机允许在同一台服务器上托管多个网站。以下是配置基于名称的虚拟主机的步骤:

为每个网站创建目录结构:
  1. # 创建网站目录
  2. mkdir -p /var/www/example1.com/htdocs
  3. mkdir -p /var/www/example2.com/htdocs
  4. # 设置目录权限
  5. chown -R apache:apache /var/www/example1.com
  6. chown -R apache:apache /var/www/example2.com
  7. chmod -R 755 /var/www
复制代码

为每个网站创建测试页面:
  1. # 为 example1.com 创建测试页面
  2. echo "<html><body><h1>Welcome to Example1.com</h1></body></html>" > /var/www/example1.com/htdocs/index.html
  3. # 为 example2.com 创建测试页面
  4. echo "<html><body><h1>Welcome to Example2.com</h1></body></html>" > /var/www/example2.com/htdocs/index.html
复制代码

创建虚拟主机配置文件:
  1. # 为 example1.com 创建配置文件
  2. vi /etc/apache2/conf.d/example1.com.conf
  3. # 添加以下内容
  4. <VirtualHost *:80>
  5.     ServerAdmin admin@example1.com
  6.     ServerName example1.com
  7.     ServerAlias www.example1.com
  8.     DocumentRoot /var/www/example1.com/htdocs
  9.     ErrorLog /var/log/apache2/example1.com-error.log
  10.     CustomLog /var/log/apache2/example1.com-access.log combined
  11. </VirtualHost>
  12. # 为 example2.com 创建配置文件
  13. vi /etc/apache2/conf.d/example2.com.conf
  14. # 添加以下内容
  15. <VirtualHost *:80>
  16.     ServerAdmin admin@example2.com
  17.     ServerName example2.com
  18.     ServerAlias www.example2.com
  19.     DocumentRoot /var/www/example2.com/htdocs
  20.     ErrorLog /var/log/apache2/example2.com-error.log
  21.     CustomLog /var/log/apache2/example2.com-access.log combined
  22. </VirtualHost>
复制代码

在 Alpine Linux 的 Apache 配置中,conf.d目录下的所有.conf文件会自动加载。因此,只需重启 Apache 服务即可:
  1. # 重启 Apache 服务
  2. service apache2 restart
复制代码

2.5 启用必要模块

Apache 提供了许多模块来扩展其功能。以下是一些常用模块的启用方法:
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 取消以下模块的注释(删除行首的 #)
  4. LoadModule rewrite_module modules/mod_rewrite.so
  5. LoadModule ssl_module modules/mod_ssl.so
  6. LoadModule headers_module modules/mod_headers.so
  7. LoadModule deflate_module modules/mod_deflate.so
  8. LoadModule expires_module modules/mod_expires.so
  9. # 重启 Apache 服务
  10. service apache2 restart
复制代码

至此,Apache Web 服务器的基础配置已经完成。接下来,我们将深入探讨更高级的配置选项。

3. Apache 高级配置

3.1 SSL/TLS 配置

为了启用 HTTPS,需要为 Apache 配置 SSL/TLS。以下是详细步骤:
  1. # 安装 OpenSSL 和 SSL 模块
  2. apk add openssl apache2-ssl
复制代码
  1. # 创建 SSL 证书目录
  2. mkdir /etc/apache2/ssl
  3. # 生成私钥
  4. openssl genrsa -out /etc/apache2/ssl/server.key 2048
  5. # 生成证书签名请求 (CSR)
  6. openssl req -new -key /etc/apache2/ssl/server.key -out /etc/apache2/ssl/server.csr
  7. # 生成自签名证书
  8. openssl x509 -req -days 365 -in /etc/apache2/ssl/server.csr -signkey /etc/apache2/ssl/server.key -out /etc/apache2/ssl/server.crt
  9. # 设置适当的权限
  10. chmod 600 /etc/apache2/ssl/server.key
  11. chmod 600 /etc/apache2/ssl/server.crt
复制代码

创建 SSL 虚拟主机配置文件:
  1. # 创建 SSL 配置文件
  2. vi /etc/apache2/conf.d/ssl.conf
  3. # 添加以下内容
  4. Listen 443
  5. SSLPassPhraseDialog  builtin
  6. SSLSessionCache         shmcb:/var/run/apache2/ssl_scache(512000)
  7. SSLSessionCacheTimeout  300
  8. SSLMutex  file:/var/run/apache2/ssl_mutex
  9. SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
  10. SSLCipherSuite HIGH:!aNULL:!MD5
  11. SSLHonorCipherOrder on
  12. <VirtualHost *:443>
  13.     ServerAdmin admin@example1.com
  14.     ServerName example1.com
  15.     ServerAlias www.example1.com
  16.     DocumentRoot /var/www/example1.com/htdocs
  17.     ErrorLog /var/log/apache2/example1.com-ssl-error.log
  18.     CustomLog /var/log/apache2/example1.com-ssl-access.log combined
  19.    
  20.     SSLEngine on
  21.     SSLCertificateFile /etc/apache2/ssl/server.crt
  22.     SSLCertificateKeyFile /etc/apache2/ssl/server.key
  23.    
  24.     <FilesMatch "\.(cgi|shtml|phtml|php)$">
  25.         SSLOptions +StdEnvVars
  26.     </FilesMatch>
  27.    
  28.     <Directory /var/www/example1.com/htdocs>
  29.         Options Indexes FollowSymLinks
  30.         AllowOverride All
  31.         Require all granted
  32.     </Directory>
  33.    
  34.     BrowserMatch "MSIE [2-5]" \
  35.         nokeepalive ssl-unclean-shutdown \
  36.         downgrade-1.0 force-response-1.0
  37. </VirtualHost>
复制代码
  1. # 重启 Apache 服务
  2. service apache2 restart
复制代码

现在,可以通过https://example1.com访问网站(浏览器可能会显示安全警告,因为使用的是自签名证书)。

3.2 Let’s Encrypt 免费证书配置(生产环境推荐)

对于生产环境,建议使用 Let’s Encrypt 提供的免费 SSL 证书:
  1. # 安装 Certbot
  2. apk add certbot certbot-apache
  3. # 获取并安装证书(替换 example1.com 和 www.example1.com 为您的域名)
  4. certbot --apache -d example1.com -d www.example1.com
  5. # 测试自动续期
  6. certbot renew --dry-run
复制代码

3.3 URL 重写与重定向

Apache 的mod_rewrite模块提供了强大的 URL 重写功能。以下是一些常见的重写规则示例:

在虚拟主机配置中添加以下内容:
  1. <Directory /var/www/example1.com/htdocs>
  2.     RewriteEngine On
  3.     RewriteCond %{HTTPS} off
  4.     RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  5. </Directory>
复制代码
  1. <Directory /var/www/example1.com/htdocs>
  2.     RewriteEngine On
  3.     RewriteCond %{HTTP_HOST} ^www\.example1\.com [NC]
  4.     RewriteRule ^(.*)$ https://example1.com/$1 [L,R=301]
  5. </Directory>
复制代码
  1. <Directory /var/www/example1.com/htdocs>
  2.     RewriteEngine On
  3.     RewriteCond %{REQUEST_FILENAME} !-d
  4.     RewriteCond %{REQUEST_FILENAME}\.php -f
  5.     RewriteRule ^(.*)$ $1.php [L]
  6. </Directory>
复制代码

3.4 访问控制与认证
  1. <Directory /var/www/example1.com/htdocs/admin>
  2.     Require ip 192.168.1.0/24
  3.     Require ip 10.0.0.5
  4. </Directory>
复制代码
  1. # 安装 htpasswd 工具
  2. apk add apache2-utils
  3. # 创建密码文件
  4. htpasswd -c /etc/apache2/.htpasswd admin
  5. # 添加更多用户
  6. htpasswd /etc/apache2/.htpasswd user2
复制代码

在虚拟主机配置中添加以下内容:
  1. <Directory /var/www/example1.com/htdocs/admin>
  2.     AuthType Basic
  3.     AuthName "Restricted Area"
  4.     AuthUserFile /etc/apache2/.htpasswd
  5.     Require valid-user
  6. </Directory>
复制代码

3.5 目录列表与自定义错误页面
  1. <Directory /var/www/example1.com/htdocs/downloads>
  2.     Options +Indexes
  3.     IndexOptions FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* IgnoreCase
  4.     HeaderName HEADER.html
  5.     ReadmeName README.html
  6. </Directory>
复制代码
  1. ErrorDocument 400 /errors/400.html
  2. ErrorDocument 401 /errors/401.html
  3. ErrorDocument 403 /errors/403.html
  4. ErrorDocument 404 /errors/404.html
  5. ErrorDocument 500 /errors/500.html
复制代码

3.6 MIME 类型配置
  1. # 添加新的 MIME 类型
  2. AddType application/x-httpd-php .php .phtml
  3. AddType application/x-httpd-php-source .phps
  4. # 添加压缩类型
  5. AddOutputFilterByType DEFLATE text/plain
  6. AddOutputFilterByType DEFLATE text/html
  7. AddOutputFilterByType DEFLATE text/xml
  8. AddOutputFilterByType DEFLATE text/css
  9. AddOutputFilterByType DEFLATE application/xml
  10. AddOutputFilterByType DEFLATE application/xhtml+xml
  11. AddOutputFilterByType DEFLATE application/rss+xml
  12. AddOutputFilterByType DEFLATE application/javascript
  13. AddOutputFilterByType DEFLATE application/x-javascript
复制代码

3.7 缓存配置
  1. <IfModule mod_expires.c>
  2.     ExpiresActive On
  3.     ExpiresByType image/jpg "access plus 1 year"
  4.     ExpiresByType image/jpeg "access plus 1 year"
  5.     ExpiresByType image/gif "access plus 1 year"
  6.     ExpiresByType image/png "access plus 1 year"
  7.     ExpiresByType text/css "access plus 1 month"
  8.     ExpiresByType application/pdf "access plus 1 month"
  9.     ExpiresByType text/x-javascript "access plus 1 month"
  10.     ExpiresByType application/x-shockwave-flash "access plus 1 month"
  11.     ExpiresByType image/x-icon "access plus 1 year"
  12.     ExpiresDefault "access plus 2 days"
  13. </IfModule>
复制代码
  1. <IfModule mod_disk_cache.c>
  2.     CacheEnable disk /
  3.     CacheRoot "/var/cache/apache2/mod_disk_cache"
  4.     CacheDirLevels 2
  5.     CacheDirLength 1
  6.     CacheDefaultExpire 3600
  7.     CacheMaxFileSize 1000000
  8.     CacheMinFileSize 1
  9. </IfModule>
复制代码

4. 安全优化

4.1 Apache 安全配置
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 添加或修改以下指令
  4. ServerTokens Prod
  5. ServerSignature Off
  6. TraceEnable Off
复制代码
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 注释掉不必要的模块
  4. # LoadModule autoindex_module modules/mod_autoindex.so
  5. # LoadModule userdir_module modules/mod_userdir.so
  6. # LoadModule info_module modules/mod_info.so
  7. # LoadModule status_module modules/mod_status.so
复制代码
  1. <FilesMatch "^\.ht">
  2.     Require all denied
  3. </FilesMatch>
  4. <DirectoryMatch "/\.git">
  5.     Require all denied
  6. </DirectoryMatch>
  7. <DirectoryMatch "/\.svn">
  8.     Require all denied
  9. </DirectoryMatch>
复制代码
  1. <IfModule mod_headers.c>
  2.     Header always append X-Frame-Options "SAMEORIGIN"
  3.     Header always set X-Content-Type-Options "nosniff"
  4.     Header always set X-XSS-Protection "1; mode=block"
  5. </IfModule>
复制代码
  1. <Directory /var/www/example1.com/htdocs>
  2.     <LimitExcept GET POST HEAD>
  3.         Require all denied
  4.     </LimitExcept>
  5. </Directory>
复制代码

4.2 Alpine Linux 系统安全加固
  1. # 更新系统
  2. apk update && apk upgrade
  3. # 设置自动更新(可选)
  4. apk add cronie
  5. rc-update add cronie default
  6. crontab -e
  7. # 添加以下内容以每周日午夜更新系统
  8. 0 0 * * 0 apk update && apk upgrade
复制代码
  1. # 安装 Fail2Ban
  2. apk add fail2ban
  3. # 创建配置文件
  4. cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
  5. # 编辑配置文件
  6. vi /etc/fail2ban/jail.local
  7. # 配置 SSH 保护
  8. [sshd]
  9. enabled = true
  10. port = 2222
  11. filter = sshd
  12. logpath = /var/log/messages
  13. maxretry = 3
  14. bantime = 3600
  15. # 配置 Apache 保护
  16. [apache-auth]
  17. enabled = true
  18. port = http,https
  19. filter = apache-auth
  20. logpath = /var/log/apache2/error.log
  21. maxretry = 3
  22. bantime = 3600
  23. # 启动 Fail2Ban 服务
  24. service fail2ban start
  25. rc-update add fail2ban default
复制代码
  1. # 安装 auditd
  2. apk add audit
  3. # 启动审计服务
  4. service auditd start
  5. rc-update add auditd default
  6. # 添加审计规则
  7. auditctl -a always,exit -F arch=b64 -S execve
  8. auditctl -a always,exit -F arch=b32 -S execve
  9. auditctl -w /etc/passwd -p wa -k identity
  10. auditctl -w /etc/group -p wa -k identity
  11. auditctl -w /etc/shadow -p wa -k identity
  12. auditctl -w /etc/sudoers -p wa -k identity
  13. auditctl -w /var/log/apache2 -p wa -k apache_logs
  14. # 保存规则
  15. auditctl -e 1
复制代码
  1. # 查看已启用的服务
  2. rc-status
  3. # 禁用不必要的服务(根据实际情况)
  4. rc-update del cronie boot
  5. rc-update del syslog boot
复制代码
  1. # 编辑 limits.conf
  2. vi /etc/security/limits.conf
  3. # 添加以下内容
  4. * soft nofile 65535
  5. * hard nofile 65535
  6. * soft nproc 4096
  7. * hard nproc 4096
复制代码

4.3 文件系统安全
  1. # 设置 Web 目录权限
  2. chown -R apache:apache /var/www
  3. find /var/www -type d -exec chmod 755 {} \;
  4. find /var/www -type f -exec chmod 644 {} \;
  5. # 设置配置文件权限
  6. chmod 640 /etc/apache2/httpd.conf
  7. chmod 640 /etc/apache2/conf.d/*.conf
  8. chmod 600 /etc/apache2/.htpasswd
  9. chmod 600 /etc/apache2/ssl/server.key
复制代码

对于高度安全的环境,可以考虑将部分目录设置为只读:
  1. # 编辑 /etc/fstab
  2. vi /etc/fstab
  3. # 添加以下内容(根据实际情况调整)
  4. /dev/sda1   /               ext4    defaults,ro        0 0
  5. /dev/sda2   /var            ext4    defaults,rw        0 0
  6. /dev/sda3   /tmp            ext4    defaults,rw        0 0
复制代码
  1. # 安装必要的工具
  2. apk add debootstrap
  3. # 创建 chroot 环境
  4. mkdir /chroot/apache
  5. debootstrap --arch=amd64 alpine /chroot/apache http://dl-cdn.alpinelinux.org/alpine/v3.19/main
  6. # 配置 chroot 环境
  7. # (这是一个复杂的过程,需要仔细配置)
复制代码

5. 性能调优

5.1 Apache 性能优化

Alpine Linux 上的 Apache 默认使用eventMPM,这是一个高性能的异步模型。以下是优化配置:
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 配置 event MPM
  4. <IfModule mpm_event_module>
  5.     StartServers             3
  6.     MinSpareThreads         75
  7.     MaxSpareThreads        250
  8.     ThreadsPerChild         25
  9.     MaxRequestWorkers      400
  10.     MaxConnectionsPerChild  10000
  11. </IfModule>
复制代码
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 配置 Keep-Alive
  4. KeepAlive On
  5. MaxKeepAliveRequests 100
  6. KeepAliveTimeout 5
复制代码
  1. # 安装 HTTP/2 模块
  2. apk add apache2-http2
  3. # 编辑 Apache 配置文件
  4. vi /etc/apache2/httpd.conf
  5. # 启用 HTTP/2 模块
  6. LoadModule http2_module modules/mod_http2.so
  7. # 在 SSL 虚拟主机中添加
  8. Protocols h2 http/1.1
复制代码
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 使用高效的日志格式
  4. LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
  5. LogFormat "%h %l %u %t "%r" %>s %b" common
  6. # 禁用主机名查找
  7. HostnameLookups Off
复制代码
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 配置内容压缩
  4. <IfModule mod_deflate.c>
  5.     AddOutputFilterByType DEFLATE text/plain
  6.     AddOutputFilterByType DEFLATE text/html
  7.     AddOutputFilterByType DEFLATE text/xml
  8.     AddOutputFilterByType DEFLATE text/css
  9.     AddOutputFilterByType DEFLATE application/xml
  10.     AddOutputFilterByType DEFLATE application/xhtml+xml
  11.     AddOutputFilterByType DEFLATE application/rss+xml
  12.     AddOutputFilterByType DEFLATE application/javascript
  13.     AddOutputFilterByType DEFLATE application/x-javascript
  14.    
  15.     # 浏览器兼容性
  16.     BrowserMatch ^Mozilla/4 gzip-only-text/html
  17.     BrowserMatch ^Mozilla/4\.0[678] no-gzip
  18.     BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  19.     Header append Vary User-Agent
  20. </IfModule>
复制代码

5.2 系统性能优化
  1. # 编辑 sysctl.conf
  2. vi /etc/sysctl.conf
  3. # 添加以下内容
  4. # 网络参数优化
  5. net.core.rmem_max = 16777216
  6. net.core.wmem_max = 16777216
  7. net.ipv4.tcp_rmem = 4096 87380 16777216
  8. net.ipv4.tcp_wmem = 4096 65536 16777216
  9. net.ipv4.tcp_fin_timeout = 30
  10. net.ipv4.tcp_keepalive_time = 1200
  11. net.ipv4.tcp_max_syn_backlog = 65536
  12. net.core.netdev_max_backlog = 65536
  13. net.ipv4.tcp_max_tw_buckets = 1440000
  14. net.ipv4.tcp_tw_reuse = 1
  15. net.ipv4.tcp_tw_recycle = 0
  16. net.ipv4.tcp_syncookies = 1
  17. net.ipv4.tcp_synack_retries = 2
  18. net.ipv4.tcp_syn_retries = 2
  19. net.ipv4.ip_local_port_range = 1024 65535
  20. # 文件系统参数优化
  21. fs.file-max = 100000
  22. fs.inotify.max_user_watches = 100000
  23. vm.swappiness = 10
  24. vm.dirty_ratio = 60
  25. vm.dirty_background_ratio = 2
  26. # 应用配置
  27. sysctl -p
复制代码
  1. # 检查当前 I/O 调度器
  2. cat /sys/block/sda/queue/scheduler
  3. # 更改 I/O 调度器为 deadline(适用于服务器环境)
  4. echo deadline > /sys/block/sda/queue/scheduler
  5. # 使更改永久生效
  6. echo "echo deadline > /sys/block/sda/queue/scheduler" >> /etc/local.d/io_scheduler.start
  7. chmod +x /etc/local.d/io_scheduler.start
  8. rc-update add local default
复制代码
  1. # 安装内存监控工具
  2. apk add htop
  3. # 编辑 sysctl.conf
  4. vi /etc/sysctl.conf
  5. # 添加以下内容
  6. vm.overcommit_memory = 1
  7. vm.overcommit_ratio = 50
  8. vm.zone_reclaim_mode = 0
  9. # 应用配置
  10. sysctl -p
复制代码

5.3 使用缓存加速
  1. # 安装 Redis
  2. apk add redis
  3. # 启动 Redis 服务
  4. service redis start
  5. rc-update add redis default
  6. # 安装 PHP Redis 扩展(如果使用 PHP)
  7. apk add php81-pecl-redis
复制代码
  1. # 安装 Memcached
  2. apk add memcached
  3. # 启动 Memcached 服务
  4. service memcached start
  5. rc-update add memcached default
  6. # 编辑 Memcached 配置
  7. vi /etc/conf.d/memcached
  8. # 优化配置
  9. MEMCACHED_OPTS="-m 512 -c 2048 -l 127.0.0.1"
复制代码
  1. # 安装 Varnish
  2. apk add varnish
  3. # 启动 Varnish 服务
  4. service varnish start
  5. rc-update add varnish default
  6. # 编辑 Varnish 配置
  7. vi /etc/varnish/default.vcl
  8. # 基本配置示例
  9. vcl 4.0;
  10. backend default {
  11.     .host = "127.0.0.1";
  12.     .port = "8080";
  13. }
  14. sub vcl_recv {
  15.     # 处理压缩
  16.     if (req.http.Accept-Encoding) {
  17.         if (req.http.Accept-Encoding ~ "gzip") {
  18.             set req.http.Accept-Encoding = "gzip";
  19.         } elsif (req.http.Accept-Encoding ~ "deflate") {
  20.             set req.http.Accept-Encoding = "deflate";
  21.         } else {
  22.             unset req.http.Accept-Encoding;
  23.         }
  24.     }
  25. }
  26. sub vcl_backend_response {
  27.     # 设置缓存时间
  28.     if (beresp.ttl > 0s) {
  29.         unset beresp.http.Set-Cookie;
  30.     }
  31. }
复制代码

5.4 使用 CDN 加速

1. 注册 Cloudflare 账户并添加域名
2. 更新域名服务器为 Cloudflare 提供的 NS
3. 配置缓存规则和页面规则
4. 启用自动 HTTPS 和 Brotli 压缩
5. 配置 WAF 规则和 DDoS 保护
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 配置真实 IP 获取
  4. RemoteIPHeader CF-Connecting-IP
  5. RemoteIPInternalProxy 173.245.48.0/20
  6. RemoteIPInternalProxy 103.21.244.0/22
  7. RemoteIPInternalProxy 103.22.200.0/22
  8. RemoteIPInternalProxy 103.31.4.0/22
  9. RemoteIPInternalProxy 141.101.64.0/18
  10. RemoteIPInternalProxy 108.162.192.0/18
  11. RemoteIPInternalProxy 190.93.240.0/20
  12. RemoteIPInternalProxy 188.114.96.0/20
  13. RemoteIPInternalProxy 197.234.240.0/22
  14. RemoteIPInternalProxy 198.41.128.0/17
  15. RemoteIPInternalProxy 162.158.0.0/15
  16. RemoteIPInternalProxy 104.16.0.0/13
  17. RemoteIPInternalProxy 104.24.0.0/14
  18. RemoteIPInternalProxy 172.64.0.0/13
  19. RemoteIPInternalProxy 131.0.72.0/22
  20. # 更新日志格式
  21. LogFormat "%a %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
复制代码

6. 监控与维护

6.1 监控 Apache 服务器
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 启用服务器状态模块
  4. LoadModule status_module modules/mod_status.so
  5. # 配置服务器状态
  6. <Location /server-status>
  7.     SetHandler server-status
  8.     Require ip 127.0.0.1 192.168.1.0/24
  9. </Location>
  10. # 扩展服务器状态
  11. ExtendedStatus On
复制代码
  1. # 编辑 Apache 配置文件
  2. vi /etc/apache2/httpd.conf
  3. # 启用服务器信息模块
  4. LoadModule info_module modules/mod_info.so
  5. # 配置服务器信息
  6. <Location /server-info>
  7.     SetHandler server-info
  8.     Require ip 127.0.0.1 192.168.1.0/24
  9. </Location>
复制代码
  1. # 安装 GoAccess
  2. apk add goaccess
  3. # 分析 Apache 访问日志
  4. goaccess /var/log/apache2/access.log -c
  5. # 生成 HTML 报告
  6. goaccess /var/log/apache2/access.log -o /var/www/localhost/htdocs/report.html --real-time-html
复制代码

6.2 系统监控
  1. # 安装 htop
  2. apk add htop
  3. # 运行 htop
  4. htop
复制代码
  1. # 安装 nmon
  2. apk add nmon
  3. # 运行 nmon
  4. nmon
复制代码
  1. # 安装 Zabbix Agent
  2. apk add zabbix-agent
  3. # 配置 Zabbix Agent
  4. vi /etc/zabbix/zabbix_agentd.conf
  5. # 设置服务器 IP
  6. Server=192.168.1.100
  7. ServerActive=192.168.1.100
  8. Hostname=webserver.example.com
  9. # 启动 Zabbix Agent
  10. service zabbix-agentd start
  11. rc-update add zabbix-agentd default
复制代码

6.3 日志管理
  1. # 安装 logrotate
  2. apk add logrotate
  3. # 创建 Apache 日志轮转配置
  4. vi /etc/logrotate.d/apache2
  5. # 添加以下内容
  6. /var/log/apache2/*.log {
  7.     daily
  8.     missingok
  9.     rotate 52
  10.     compress
  11.     delaycompress
  12.     notifempty
  13.     create 644 apache apache
  14.     sharedscripts
  15.     postrotate
  16.         service apache2 reload > /dev/null 2>&1 || true
  17.     endscript
  18. }
复制代码
  1. # 安装 rsyslog
  2. apk add rsyslog
  3. # 配置 rsyslog
  4. vi /etc/rsyslog.conf
  5. # 添加以下内容以发送 Apache 日志到远程服务器
  6. module(load="imfile")
  7. input(type="imfile"
  8.       File="/var/log/apache2/access.log"
  9.       Tag="apache-access:"
  10.       Severity="info"
  11.       Facility="local6")
  12. input(type="imfile"
  13.       File="/var/log/apache2/error.log"
  14.       Tag="apache-error:"
  15.       Severity="error"
  16.       Facility="local6")
  17. local6.* @192.168.1.200:514
  18. # 启动 rsyslog
  19. service rsyslog start
  20. rc-update add rsyslog default
复制代码

6.4 备份与恢复
  1. # 创建备份脚本
  2. vi /usr/local/bin/backup.sh
  3. # 添加以下内容
  4. #!/bin/sh
  5. # 设置变量
  6. BACKUP_DIR="/backup"
  7. DATE=$(date +%Y%m%d)
  8. WEB_DIR="/var/www"
  9. APACHE_CONF="/etc/apache2"
  10. # 创建备份目录
  11. mkdir -p $BACKUP_DIR/$DATE
  12. # 备份网站文件
  13. tar -czf $BACKUP_DIR/$DATE/web_files.tar.gz $WEB_DIR
  14. # 备份 Apache 配置
  15. tar -czf $BACKUP_DIR/$DATE/apache_config.tar.gz $APACHE_CONF
  16. # 备份数据库(如果有)
  17. # mysqldump -u root -p'password' --all-databases | gzip > $BACKUP_DIR/$DATE/mysql_backup.sql.gz
  18. # 清理旧备份(保留最近 7 天)
  19. find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} \;
  20. # 设置脚本可执行权限
  21. chmod +x /usr/local/bin/backup.sh
复制代码
  1. # 编辑 crontab
  2. crontab -e
  3. # 添加以下内容以每天凌晨 2 点执行备份
  4. 0 2 * * * /usr/local/bin/backup.sh
复制代码
  1. # 恢复网站文件
  2. tar -xzf /backup/20231101/web_files.tar.gz -C /
  3. # 恢复 Apache 配置
  4. tar -xzf /backup/20231101/apache_config.tar.gz -C /
  5. # 重启 Apache 服务
  6. service apache2 restart
复制代码

6.5 故障排除

1. Apache 无法启动
  1. # 检查配置文件语法
  2. apache2ctl configtest
  3. # 查看错误日志
  4. tail -f /var/log/apache2/error.log
  5. # 检查端口占用
  6. netstat -tlnp | grep :80
复制代码

1. 网站访问缓慢
  1. # 检查系统资源使用情况
  2. htop
  3. # 检查 Apache 状态
  4. wget http://localhost/server-status
  5. # 检查网络连接
  6. netstat -an | grep :80 | wc -l
复制代码

1. SSL 证书问题
  1. # 检查证书有效期
  2. openssl x509 -in /etc/apache2/ssl/server.crt -text -noout | grep "Not After"
  3. # 测试 SSL 连接
  4. openssl s_client -connect example1.com:443
复制代码
  1. # 安装性能分析工具
  2. apk add sysstat
  3. # 启用系统活动报告
  4. vi /etc/sysconfig/sysstat
  5. # 设置 ENABLED="true"
  6. # 启动 sysstat 服务
  7. service sysstat start
  8. rc-update add sysstat default
  9. # 生成系统活动报告
  10. sar -u 1 5
复制代码

7. 总结

本教程详细介绍了在 Alpine Linux 上部署和配置 Apache Web 服务器的全过程,从基础环境搭建到服务配置,再到安全优化与性能调优。通过本教程,读者应该能够:

1. 成功安装和配置 Alpine Linux 操作系统
2. 部署和配置 Apache Web 服务器
3. 设置虚拟主机、SSL/TLS 和其他高级功能
4. 实施全面的安全优化措施
5. 进行系统和服务器的性能调优
6. 建立有效的监控和维护机制

Alpine Linux 的轻量级特性与 Apache Web 服务器的强大功能相结合,提供了一个高效、安全且易于维护的 Web 服务环境。这种组合特别适合现代云计算和容器化部署场景,能够有效降低资源消耗同时提供出色的性能表现。

随着技术的不断发展,建议读者持续关注 Alpine Linux 和 Apache 的最新版本和安全更新,定期评估和优化系统配置,以确保 Web 服务环境的稳定性和安全性。

通过遵循本教程中的最佳实践和优化建议,您可以构建一个既轻量又强大的 Web 服务器环境,为各种 Web 应用提供可靠的服务支持。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

手机版|联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.

>