活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

Rocky Linux云服务搭建从入门到精通掌握企业级开源操作系统在云端部署的完整流程与实用技巧解决实际应用中的常见问题提升系统稳定性与安全性

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-29 01:40:02 | 显示全部楼层 |阅读模式

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

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

x
1. Rocky Linux简介与云服务优势

Rocky Linux是一个社区支持的企业级操作系统,由CentOS创始人Gregory Kurtzer创建,旨在作为CentOS的后继者。它完全兼容Red Hat Enterprise Linux (RHEL),提供了稳定、安全且高性能的操作系统环境,非常适合企业级应用和云服务部署。

1.1 Rocky Linux的特点

• 稳定性:基于RHEL源代码构建,提供长期支持版本
• 安全性:定期安全更新和补丁
• 兼容性:与RHEL完全二进制兼容
• 社区支持:活跃的社区提供技术支持和持续开发
• 免费使用:无需订阅费用,降低企业成本

1.2 Rocky Linux在云服务中的优势

• 成本效益:作为免费的企业级操作系统,大幅降低云服务部署成本
• 可靠性:适合需要长时间稳定运行的企业应用
• 灵活性:支持各种云平台和虚拟化技术
• 安全性:内置安全功能和SELinux支持
• 生态系统:丰富的软件包和工具支持

2. Rocky Linux基础知识

2.1 系统架构

Rocky Linux支持多种处理器架构,包括:

• x86_64 (Intel/AMD 64位)
• ARM64 (aarch64)
• POWER (ppc64le)

2.2 包管理系统

Rocky Linux使用DNF(Dandified YUM)作为默认的包管理器,它是YUM的下一代版本,提供了更快的依赖解析和更好的性能。

基本DNF命令示例:
  1. # 更新软件包列表
  2. sudo dnf check-update
  3. # 安装软件包
  4. sudo dnf install package_name
  5. # 卸载软件包
  6. sudo dnf remove package_name
  7. # 搜索软件包
  8. sudo dnf search keyword
  9. # 查看已安装的软件包
  10. sudo dnf list installed
  11. # 清理缓存
  12. sudo dnf clean all
复制代码

2.3 系统服务管理

Rocky Linux使用systemd作为系统和服务管理器:
  1. # 启动服务
  2. sudo systemctl start service_name
  3. # 停止服务
  4. sudo systemctl stop service_name
  5. # 重启服务
  6. sudo systemctl restart service_name
  7. # 启用服务开机自启
  8. sudo systemctl enable service_name
  9. # 禁用服务开机自启
  10. sudo systemctl disable service_name
  11. # 查看服务状态
  12. sudo systemctl status service_name
复制代码

3. 云服务环境准备

3.1 主流云服务提供商选择

Rocky Linux可以在各大云服务提供商上部署,包括:

• Amazon Web Services (AWS)
• Microsoft Azure
• Google Cloud Platform (GCP)
• Alibaba Cloud
• 腾讯云
• 华为云

3.2 云服务账户创建与配置

以AWS为例,创建和配置云服务环境:

1. 注册AWS账户
2. 完成身份验证
3. 设置IAM用户和权限
4. 配置安全组(防火墙规则)
5. 生成SSH密钥对
  1. # 生成SSH密钥对
  2. ssh-keygen -t rsa -b 4096 -f ~/.ssh/rocky-cloud-key
  3. # 将公钥上传到云服务提供商
  4. cat ~/.ssh/rocky-cloud-key.pub
复制代码

3.3 网络规划

在部署Rocky Linux云服务器前,需要进行网络规划:

• VPC设计:确定虚拟私有云的IP地址范围
• 子网划分:根据功能划分公共子网和私有子网
• 安全组配置:设置入站和出站规则
• 负载均衡:如需要高可用性,规划负载均衡器

4. Rocky Linux在云端的安装与配置

4.1 在AWS上部署Rocky Linux

1. 登录AWS管理控制台
2. 导航到EC2服务
3. 点击”启动实例”
4. 在AWS Marketplace中搜索”Rocky Linux”
5. 选择合适的Rocky Linux AMI
6. 选择实例类型(如t3.micro用于测试,m5.large用于生产)
7. 配置实例详情(网络、子网等)
8. 添加存储(根据需求调整EBS大小)
9. 配置安全组(开放SSH、HTTP、HTTPS等端口)
10. 选择或创建SSH密钥对
11. 启动实例
  1. # 安装AWS CLI
  2. sudo dnf install awscli -y
  3. # 配置AWS CLI
  4. aws configure
  5. # 创建Rocky Linux实例
  6. aws ec2 run-instances \
  7.     --image-id ami-0abcdef1234567890 \  # 替换为实际的Rocky Linux AMI ID
  8.     --instance-type t3.micro \
  9.     --key-name rocky-cloud-key \
  10.     --security-group-ids sg-0abcdef1234567890 \
  11.     --subnet-id subnet-0abcdef1234567890 \
  12.     --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=Rocky-Linux-Server}]'
复制代码

4.2 初始系统配置
  1. # 通过SSH连接到实例
  2. ssh -i ~/.ssh/rocky-cloud-key rocky@public-ip-address
复制代码
  1. # 更新系统
  2. sudo dnf update -y
  3. # 重启系统(如果需要)
  4. sudo reboot
复制代码
  1. # 创建新用户
  2. sudo adduser adminuser
  3. # 设置密码
  4. sudo passwd adminuser
  5. # 将用户添加到wheel组(sudo权限)
  6. sudo usermod -aG wheel adminuser
  7. # 切换到新用户
  8. su - adminuser
复制代码
  1. # 查看当前主机名
  2. hostnamectl
  3. # 设置主机名
  4. sudo hostnamectl set-hostname rocky-server.example.com
  5. # 验证主机名
  6. hostnamectl status
复制代码
  1. # 查看当前时区
  2. timedatectl
  3. # 列出所有可用时区
  4. timedatectl list-timezones
  5. # 设置时区(例如:上海)
  6. sudo timedatectl set-timezone Asia/Shanghai
  7. # 验证时区设置
  8. timedatectl
复制代码
  1. # 查看网络接口
  2. ip addr show
  3. # 查看网络配置文件
  4. ls /etc/sysconfig/network-scripts/
  5. # 编辑网络配置文件(例如:ifcfg-eth0)
  6. sudo vi /etc/sysconfig/network-scripts/ifcfg-eth0
  7. # 示例配置:
  8. TYPE=Ethernet
  9. BOOTPROTO=dhcp
  10. DEFROUTE=yes
  11. PEERDNS=yes
  12. PEERROUTES=yes
  13. IPV4_FAILURE_FATAL=no
  14. IPV6INIT=yes
  15. IPV6_AUTOCONF=yes
  16. IPV6_DEFROUTE=yes
  17. IPV6_PEERDNS=yes
  18. IPV6_PEERROUTES=yes
  19. IPV6_FAILURE_FATAL=no
  20. NAME=eth0
  21. DEVICE=eth0
  22. ONBOOT=yes
  23. # 重启网络服务
  24. sudo systemctl restart NetworkManager
复制代码

5. 系统优化与安全加固

5.1 系统安全加固

Rocky Linux使用firewalld作为默认的防火墙管理工具:
  1. # 安装firewalld
  2. sudo dnf install firewalld -y
  3. # 启动并启用firewalld
  4. sudo systemctl start firewalld
  5. sudo systemctl enable firewalld
  6. # 检查firewalld状态
  7. sudo systemctl status firewalld
  8. # 查看默认区域
  9. sudo firewall-cmd --get-default-zone
  10. # 查看活动区域
  11. sudo firewall-cmd --get-active-zones
  12. # 查看当前区域开放的端口
  13. sudo firewall-cmd --list-all
  14. # 开放端口(例如:HTTP 80端口)
  15. sudo firewall-cmd --permanent --add-service=http
  16. sudo firewall-cmd --reload
  17. # 开放自定义端口(例如:8080端口)
  18. sudo firewall-cmd --permanent --add-port=8080/tcp
  19. sudo firewall-cmd --reload
  20. # 移除端口
  21. sudo firewall-cmd --permanent --remove-service=http
  22. sudo firewall-cmd --reload
复制代码

SELinux(Security-Enhanced Linux)是Linux内核的安全模块,提供强制访问控制(MAC):
  1. # 检查SELinux状态
  2. getenforce
  3. # 查看SELinux模式
  4. sestatus
  5. # 临时设置SELinux为宽松模式
  6. sudo setenforce 0
  7. # 临时设置SELinux为强制模式
  8. sudo setenforce 1
  9. # 永久修改SELinux配置
  10. sudo vi /etc/selinux/config
  11. # 将SELINUX=enforcing改为:
  12. SELINUX=disabled  # 禁用SELinux
  13. SELINUX=permissive  # 宽松模式
  14. SELINUX=enforcing  # 强制模式(推荐)
  15. # 查看文件的安全上下文
  16. ls -Z /path/to/file
  17. # 修改文件的安全上下文
  18. sudo chcon -t httpd_sys_content_t /var/www/html/index.html
  19. # 恢复文件默认安全上下文
  20. sudo restorecon -v /var/www/html/index.html
  21. # 查看SELinux布尔值
  22. getsebool -a
  23. # 设置SELinux布尔值
  24. sudo setsebool -P httpd_can_network_connect on
复制代码
  1. # 编辑SSH配置文件
  2. sudo vi /etc/ssh/sshd_config
  3. # 修改以下配置:
  4. Port 2222  # 更改默认端口
  5. PermitRootLogin no  # 禁止root登录
  6. PasswordAuthentication no  # 禁用密码认证,仅允许密钥认证
  7. PermitEmptyPasswords no  # 禁止空密码
  8. X11Forwarding no  # 禁用X11转发
  9. MaxAuthTries 3  # 最大认证尝试次数
  10. ClientAliveInterval 300  # 客户端活动间隔
  11. ClientAliveCountMax 0  # 最大客户端活动计数
  12. # 重启SSH服务
  13. sudo systemctl restart sshd
  14. # 添加防火墙规则允许新的SSH端口
  15. sudo firewall-cmd --permanent --add-port=2222/tcp
  16. sudo firewall-cmd --reload
复制代码
  1. # 安装EPEL仓库
  2. sudo dnf install epel-release -y
  3. # 安装fail2ban
  4. sudo dnf install fail2ban -y
  5. # 启动并启用fail2ban
  6. sudo systemctl start fail2ban
  7. sudo systemctl enable fail2ban
  8. # 创建本地配置文件
  9. sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
  10. # 编辑配置文件
  11. sudo vi /etc/fail2ban/jail.local
  12. # 配置SSH保护
  13. [sshd]
  14. enabled = true
  15. port = 2222
  16. filter = sshd
  17. logpath = /var/log/secure
  18. maxretry = 3
  19. bantime = 3600
  20. findtime = 600
  21. # 重启fail2ban服务
  22. sudo systemctl restart fail2ban
  23. # 查看fail2ban状态
  24. sudo fail2ban-client status
  25. sudo fail2ban-client status sshd
复制代码

5.2 系统性能优化
  1. # 编辑sysctl配置文件
  2. sudo 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 = 8192
  12. net.ipv4.tcp_max_tw_buckets = 5000
  13. net.ipv4.tcp_tw_reuse = 1
  14. net.ipv4.tcp_tw_recycle = 1
  15. net.ipv4.tcp_syncookies = 1
  16. net.ipv4.tcp_congestion_control = bbr
  17. # 文件系统优化
  18. fs.file-max = 100000
  19. fs.inotify.max_user_watches = 1000000
  20. # 虚拟内存优化
  21. vm.swappiness = 10
  22. vm.dirty_ratio = 60
  23. vm.dirty_background_ratio = 2
  24. # 应用配置
  25. sudo sysctl -p
复制代码
  1. # 查看当前文件系统
  2. df -hT
  3. # 查看磁盘I/O统计
  4. iostat -x 1
  5. # 检查文件系统
  6. sudo fsck -t ext4 /dev/sda1
  7. # 调整文件系统参数(以ext4为例)
  8. sudo tune2fs -o journal_data_writeback /dev/sda1
  9. sudo tune2fs -O ^has_journal /dev/sda1
  10. # 设置noatime选项提升性能
  11. sudo vi /etc/fstab
  12. # 修改挂载选项,添加noatime:
  13. /dev/sda1 / ext4 defaults,noatime 0 0
  14. # 重新挂载文件系统
  15. sudo mount -o remount /
复制代码
  1. # 编辑limits.conf文件
  2. sudo vi /etc/security/limits.conf
  3. # 添加或修改以下限制:
  4. * soft nofile 65536
  5. * hard nofile 65536
  6. * soft nproc 32768
  7. * hard nproc 32768
  8. * soft core unlimited
  9. * hard core unlimited
  10. # 编辑systemd系统配置
  11. sudo vi /etc/systemd/system.conf
  12. # 修改以下参数:
  13. DefaultLimitNOFILE=65536
  14. DefaultLimitNPROC=32768
  15. # 重启systemd
  16. sudo systemctl daemon-reexec
复制代码

6. 常用服务部署

6.1 Web服务器部署
  1. # 安装EPEL仓库
  2. sudo dnf install epel-release -y
  3. # 安装Nginx
  4. sudo dnf install nginx -y
  5. # 启动并启用Nginx
  6. sudo systemctl start nginx
  7. sudo systemctl enable nginx
  8. # 检查Nginx状态
  9. sudo systemctl status nginx
  10. # 配置防火墙允许HTTP和HTTPS
  11. sudo firewall-cmd --permanent --add-service=http
  12. sudo firewall-cmd --permanent --add-service=https
  13. sudo firewall-cmd --reload
  14. # 创建网站目录
  15. sudo mkdir -p /var/www/example.com/html
  16. sudo chown -R nginx:nginx /var/www/example.com/html
  17. sudo chmod -R 755 /var/www/example.com
  18. # 创建示例页面
  19. sudo vi /var/www/example.com/html/index.html
  20. # 添加以下内容:
  21. <!DOCTYPE html>
  22. <html>
  23. <head>
  24.     <title>Welcome to Example.com!</title>
  25. </head>
  26. <body>
  27.     <h1>Success! The Nginx server is working!</h1>
  28. </body>
  29. </html>
  30. # 创建Nginx配置文件
  31. sudo vi /etc/nginx/conf.d/example.com.conf
  32. # 添加以下配置:
  33. server {
  34.     listen 80;
  35.     server_name example.com www.example.com;
  36.     root /var/www/example.com/html;
  37.     index index.html;
  38.     location / {
  39.         try_files $uri $uri/ =404;
  40.     }
  41.     error_page 404 /404.html;
  42.     error_page 500 502 503 504 /50x.html;
  43.     location = /50x.html {
  44.         root /usr/share/nginx/html;
  45.     }
  46. }
  47. # 测试Nginx配置
  48. sudo nginx -t
  49. # 重新加载Nginx配置
  50. sudo systemctl reload nginx
复制代码
  1. # 安装Apache
  2. sudo dnf install httpd -y
  3. # 启动并启用Apache
  4. sudo systemctl start httpd
  5. sudo systemctl enable httpd
  6. # 检查Apache状态
  7. sudo systemctl status httpd
  8. # 配置防火墙允许HTTP和HTTPS
  9. sudo firewall-cmd --permanent --add-service=http
  10. sudo firewall-cmd --permanent --add-service=https
  11. sudo firewall-cmd --reload
  12. # 创建网站目录
  13. sudo mkdir -p /var/www/example.com/html
  14. sudo chown -R apache:apache /var/www/example.com/html
  15. sudo chmod -R 755 /var/www/example.com
  16. # 创建示例页面
  17. sudo vi /var/www/example.com/html/index.html
  18. # 添加以下内容:
  19. <!DOCTYPE html>
  20. <html>
  21. <head>
  22.     <title>Welcome to Example.com!</title>
  23. </head>
  24. <body>
  25.     <h1>Success! The Apache server is working!</h1>
  26. </body>
  27. </html>
  28. # 创建Apache配置文件
  29. sudo vi /etc/httpd/conf.d/example.com.conf
  30. # 添加以下配置:
  31. <VirtualHost *:80>
  32.     ServerName example.com
  33.     ServerAlias www.example.com
  34.     DocumentRoot /var/www/example.com/html
  35.    
  36.     <Directory /var/www/example.com/html>
  37.         Options Indexes FollowSymLinks
  38.         AllowOverride All
  39.         Require all granted
  40.     </Directory>
  41.    
  42.     ErrorLog /var/log/httpd/example.com-error.log
  43.     CustomLog /var/log/httpd/example.com-access.log combined
  44. </VirtualHost>
  45. # 检查Apache配置
  46. sudo apachectl configtest
  47. # 重新加载Apache配置
  48. sudo systemctl reload httpd
复制代码

6.2 数据库服务器部署
  1. # 安装MariaDB服务器
  2. sudo dnf install mariadb-server -y
  3. # 启动并启用MariaDB
  4. sudo systemctl start mariadb
  5. sudo systemctl enable mariadb
  6. # 检查MariaDB状态
  7. sudo systemctl status mariadb
  8. # 运行安全安装脚本
  9. sudo mysql_secure_installation
  10. # 登录到MariaDB
  11. mysql -u root -p
  12. # 创建数据库和用户
  13. CREATE DATABASE exampledb;
  14. CREATE USER 'exampleuser'@'localhost' IDENTIFIED BY 'password';
  15. GRANT ALL PRIVILEGES ON exampledb.* TO 'exampleuser'@'localhost';
  16. FLUSH PRIVILEGES;
  17. EXIT;
  18. # 配置防火墙允许MySQL端口(如需远程访问)
  19. sudo firewall-cmd --permanent --add-service=mysql
  20. sudo firewall-cmd --reload
  21. # 编辑MariaDB配置文件
  22. sudo vi /etc/my.cnf.d/mariadb-server.cnf
  23. # 添加或修改以下配置:
  24. [mysqld]
  25. character-set-server = utf8mb4
  26. collation-server = utf8mb4_unicode_ci
  27. max_connections = 200
  28. innodb_buffer_pool_size = 2G  # 根据服务器内存调整
  29. innodb_log_file_size = 256M
  30. slow_query_log = 1
  31. slow_query_log_file = /var/log/mariadb/slow.log
  32. long_query_time = 2
  33. # 重启MariaDB服务
  34. sudo systemctl restart mariadb
复制代码
  1. # 安装PostgreSQL服务器
  2. sudo dnf install postgresql-server postgresql-contrib -y
  3. # 初始化数据库集群
  4. sudo postgresql-setup --initdb
  5. # 启动并启用PostgreSQL
  6. sudo systemctl start postgresql
  7. sudo systemctl enable postgresql
  8. # 检查PostgreSQL状态
  9. sudo systemctl status postgresql
  10. # 切换到postgres用户
  11. sudo -i -u postgres
  12. # 创建数据库和用户
  13. createdb exampledb
  14. createuser --interactive
  15. # 设置密码
  16. psql -c "ALTER USER exampleuser WITH PASSWORD 'password';"
  17. # 授予数据库权限
  18. psql -c "GRANT ALL PRIVILEGES ON DATABASE exampledb TO exampleuser;"
  19. # 退出postgres用户
  20. exit
  21. # 配置防火墙允许PostgreSQL端口(如需远程访问)
  22. sudo firewall-cmd --permanent --add-service=postgresql
  23. sudo firewall-cmd --reload
  24. # 编辑PostgreSQL配置文件
  25. sudo vi /var/lib/pgsql/data/postgresql.conf
  26. # 添加或修改以下配置:
  27. listen_addresses = 'localhost'  # 或 '*' 允许所有IP连接
  28. max_connections = 100
  29. shared_buffers = 128MB  # 根据服务器内存调整
  30. effective_cache_size = 4GB
  31. maintenance_work_mem = 64MB
  32. checkpoint_completion_target = 0.9
  33. wal_buffers = 16MB
  34. default_statistics_target = 100
  35. random_page_cost = 1.1
  36. effective_io_concurrency = 200
  37. work_mem = 4MB
  38. min_wal_size = 1GB
  39. max_wal_size = 4GB
  40. # 编辑客户端认证配置文件
  41. sudo vi /var/lib/pgsql/data/pg_hba.conf
  42. # 添加或修改以下配置以允许远程连接:
  43. # TYPE  DATABASE        USER            ADDRESS                 METHOD
  44. host    all             all             0.0.0.0/0               md5
  45. # 重启PostgreSQL服务
  46. sudo systemctl restart postgresql
复制代码

6.3 安装PHP
  1. # 安装EPEL和Remi仓库
  2. sudo dnf install epel-release -y
  3. sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm -y
  4. # 安装PHP及常用扩展
  5. sudo dnf module enable php:remi-8.1 -y
  6. sudo dnf install php php-cli php-fpm php-mysqlnd php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath php-json -y
  7. # 检查PHP版本
  8. php -v
  9. # 配置PHP-FPM
  10. sudo vi /etc/php-fpm.d/www.conf
  11. # 修改以下配置:
  12. user = nginx  # 如果使用Nginx
  13. ; user = apache  # 如果使用Apache
  14. group = nginx  # 如果使用Nginx
  15. ; group = apache  # 如果使用Apache
  16. listen = /var/run/php-fpm/php-fpm.sock
  17. listen.owner = nginx
  18. listen.group = nginx
  19. listen.mode = 0660
  20. pm = dynamic
  21. pm.max_children = 50
  22. pm.start_servers = 5
  23. pm.min_spare_servers = 5
  24. pm.max_spare_servers = 35
  25. # 启动并启用PHP-FPM
  26. sudo systemctl start php-fpm
  27. sudo systemctl enable php-fpm
  28. # 检查PHP-FPM状态
  29. sudo systemctl status php-fpm
  30. # 创建PHP测试文件
  31. sudo vi /var/www/example.com/html/info.php
  32. # 添加以下内容:
  33. <?php
  34. phpinfo();
  35. ?>
  36. # 如果使用Nginx,修改Nginx配置以支持PHP
  37. sudo vi /etc/nginx/conf.d/example.com.conf
  38. # 添加以下配置:
  39. server {
  40.     listen 80;
  41.     server_name example.com www.example.com;
  42.     root /var/www/example.com/html;
  43.     index index.php index.html;
  44.     location / {
  45.         try_files $uri $uri/ =404;
  46.     }
  47.     location ~ \.php$ {
  48.         fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
  49.         fastcgi_index index.php;
  50.         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  51.         include fastcgi_params;
  52.     }
  53.     error_page 404 /404.html;
  54.     error_page 500 502 503 504 /50x.html;
  55.     location = /50x.html {
  56.         root /usr/share/nginx/html;
  57.     }
  58. }
  59. # 测试Nginx配置
  60. sudo nginx -t
  61. # 重新加载Nginx配置
  62. sudo systemctl reload nginx
  63. # 如果使用Apache,安装PHP模块并重启Apache
  64. sudo dnf install php libapache2-mod-php -y
  65. sudo systemctl restart httpd
复制代码

6.4 安装Docker
  1. # 安装必要的包
  2. sudo dnf install -y dnf-utils device-mapper-persistent-data lvm2
  3. # 添加Docker仓库
  4. sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
  5. # 安装Docker
  6. sudo dnf install -y docker-ce docker-ce-cli containerd.io
  7. # 启动并启用Docker
  8. sudo systemctl start docker
  9. sudo systemctl enable docker
  10. # 检查Docker状态
  11. sudo systemctl status docker
  12. # 将用户添加到docker组(避免使用sudo)
  13. sudo usermod -aG docker $USER
  14. # 重新登录以应用组更改
  15. # 验证Docker安装
  16. docker run hello-world
  17. # 配置Docker镜像加速器(可选)
  18. sudo mkdir -p /etc/docker
  19. sudo vi /etc/docker/daemon.json
  20. # 添加以下内容(使用阿里云镜像加速器为例):
  21. {
  22.   "registry-mirrors": ["https://<your-mirror-id>.mirror.aliyuncs.com"]
  23. }
  24. # 重启Docker服务
  25. sudo systemctl restart docker
  26. # 安装Docker Compose
  27. sudo dnf install -y docker-compose-plugin
  28. # 验证Docker Compose安装
  29. docker compose version
复制代码

7. 监控与维护

7.1 系统监控工具
  1. # 安装htop
  2. sudo dnf install htop -y
  3. # 使用top命令
  4. top
  5. # 使用htop命令
  6. htop
复制代码
  1. # 安装sysstat包
  2. sudo dnf install sysstat -y
  3. # 启用并启动sysstat
  4. sudo systemctl enable sysstat
  5. sudo systemctl start sysstat
  6. # 使用vmstat查看内存、进程和CPU活动
  7. vmstat 1 5
  8. # 使用iostat查看CPU和I/O统计信息
  9. iostat -xz 1
  10. # 使用mpstat查看CPU统计信息
  11. mpstat -P ALL 1
复制代码
  1. # 安装nmon
  2. sudo dnf install nmon -y
  3. # 运行nmon
  4. nmon
复制代码

7.2 日志管理
  1. # 查看所有日志
  2. sudo journalctl
  3. # 查看特定服务的日志
  4. sudo journalctl -u nginx.service
  5. # 查看最近的日志
  6. sudo journalctl -n 100
  7. # 实时查看日志
  8. sudo journalctl -f
  9. # 查看特定时间段的日志
  10. sudo journalctl --since "2023-01-01" --until "2023-01-02"
  11. # 查看内核日志
  12. sudo journalctl -k
  13. # 限制日志输出数量
  14. sudo journalctl -n 50
  15. # 清理旧日志
  16. sudo journalctl --vacuum-size=100M
复制代码
  1. # 查看logrotate配置
  2. ls /etc/logrotate.d/
  3. # 编辑Nginx的logrotate配置
  4. sudo vi /etc/logrotate.d/nginx
  5. # 示例配置:
  6. /var/log/nginx/*.log {
  7.     daily
  8.     missingok
  9.     rotate 52
  10.     compress
  11.     delaycompress
  12.     notifempty
  13.     create 640 nginx adm
  14.     sharedscripts
  15.     postrotate
  16.         if [ -f /var/run/nginx.pid ]; then
  17.             kill -USR1 `cat /var/run/nginx.pid`
  18.         fi
  19.     endscript
  20. }
  21. # 测试logrotate配置
  22. sudo logrotate -d /etc/logrotate.d/nginx
  23. # 手动运行logrotate
  24. sudo logrotate -f /etc/logrotate.d/nginx
复制代码

7.3 安装和使用监控解决方案
  1. # 安装Zabbix仓库
  2. sudo rpm -Uvh https://repo.zabbix.com/zabbix/6.0/rhel/9/x86_64/zabbix-release-6.0-4.el9.noarch.rpm
  3. sudo dnf clean all
  4. # 安装Zabbix服务器、前端和代理
  5. sudo dnf install zabbix-server-mysql zabbix-web-mysql zabbix-apache-conf zabbix-sql-scripts zabbix-selinux-policy zabbix-agent -y
  6. # 创建初始数据库
  7. mysql -uroot -p
  8. create database zabbix character set utf8mb4 collate utf8mb4_bin;
  9. create user zabbix@localhost identified by 'password';
  10. grant all privileges on zabbix.* to zabbix@localhost;
  11. set global log_bin_trust_function_creators = 1;
  12. quit;
  13. # 导入初始架构和数据
  14. zcat /usr/share/doc/zabbix-sql-scripts/mysql/server.sql.gz | mysql -uzabbix -p zabbix
  15. # 导入数据库后禁用log_bin_trust_function_creators
  16. mysql -uroot -p
  17. set global log_bin_trust_function_creators = 0;
  18. quit;
  19. # 为Zabbix服务器配置数据库
  20. sudo vi /etc/zabbix/zabbix_server.conf
  21. # 修改以下配置:
  22. DBPassword=password
  23. # 为Zabbix前端配置PHP时区
  24. sudo vi /etc/php-fpm.d/zabbix.conf
  25. # 修改以下配置:
  26. php_value[date.timezone] = Asia/Shanghai
  27. # 启动Zabbix服务器和代理进程
  28. sudo systemctl restart zabbix-server zabbix-agent httpd php-fpm
  29. sudo systemctl enable zabbix-server zabbix-agent httpd php-fpm
  30. # 配置防火墙允许Zabbix端口
  31. sudo firewall-cmd --permanent --add-service=http
  32. sudo firewall-cmd --permanent --add-port=10051/tcp
  33. sudo firewall-cmd --reload
  34. # 访问Zabbix前端
  35. # http://<server_ip_or_name>/zabbix
复制代码
  1. # 创建Prometheus用户
  2. sudo useradd --no-create-home --shell /bin/false prometheus
  3. # 创建必要的目录
  4. sudo mkdir /etc/prometheus
  5. sudo mkdir /var/lib/prometheus
  6. # 下载Prometheus
  7. cd /tmp
  8. wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
  9. tar -xvf prometheus-2.37.0.linux-amd64.tar.gz
  10. # 复制二进制文件
  11. sudo cp prometheus-2.37.0.linux-amd64/prometheus /usr/local/bin/
  12. sudo cp prometheus-2.37.0.linux-amd64/promtool /usr/local/bin/
  13. # 复制配置文件
  14. sudo cp -r prometheus-2.37.0.linux-amd64/consoles /etc/prometheus
  15. sudo cp -r prometheus-2.37.0.linux-amd64/console_libraries /etc/prometheus
  16. # 设置目录权限
  17. sudo chown -R prometheus:prometheus /etc/prometheus
  18. sudo chown -R prometheus:prometheus /var/lib/prometheus
  19. # 创建Prometheus配置文件
  20. sudo vi /etc/prometheus/prometheus.yml
  21. # 添加以下基本配置:
  22. global:
  23.   scrape_interval: 15s
  24. scrape_configs:
  25.   - job_name: 'prometheus'
  26.     scrape_interval: 5s
  27.     static_configs:
  28.       - targets: ['localhost:9090']
  29.   - job_name: 'node_exporter'
  30.     scrape_interval: 5s
  31.     static_configs:
  32.       - targets: ['localhost:9100']
  33. # 创建systemd服务文件
  34. sudo vi /etc/systemd/system/prometheus.service
  35. # 添加以下内容:
  36. [Unit]
  37. Description=Prometheus
  38. Wants=network-online.target
  39. After=network-online.target
  40. [Service]
  41. User=prometheus
  42. Group=prometheus
  43. Type=simple
  44. ExecStart=/usr/local/bin/prometheus \
  45.     --config.file /etc/prometheus/prometheus.yml \
  46.     --storage.tsdb.path /var/lib/prometheus/ \
  47.     --web.console.templates=/etc/prometheus/consoles \
  48.     --web.console.libraries=/etc/prometheus/console_libraries
  49. [Install]
  50. WantedBy=multi-user.target
  51. # 启动Prometheus服务
  52. sudo systemctl daemon-reload
  53. sudo systemctl start prometheus
  54. sudo systemctl enable prometheus
  55. # 检查Prometheus状态
  56. sudo systemctl status prometheus
  57. # 安装Node Exporter
  58. sudo useradd --no-create-home --shell /bin/false node_exporter
  59. # 下载Node Exporter
  60. cd /tmp
  61. wget https://github.com/prometheus/node_exporter/releases/download/v1.4.0/node_exporter-1.4.0.linux-amd64.tar.gz
  62. tar -xvf node_exporter-1.4.0.linux-amd64.tar.gz
  63. # 复制二进制文件
  64. sudo cp node_exporter-1.4.0.linux-amd64/node_exporter /usr/local/bin/
  65. # 设置权限
  66. sudo chown node_exporter:node_exporter /usr/local/bin/node_exporter
  67. # 创建systemd服务文件
  68. sudo vi /etc/systemd/system/node_exporter.service
  69. # 添加以下内容:
  70. [Unit]
  71. Description=Node Exporter
  72. Wants=network-online.target
  73. After=network-online.target
  74. [Service]
  75. User=node_exporter
  76. Group=node_exporter
  77. Type=simple
  78. ExecStart=/usr/local/bin/node_exporter
  79. [Install]
  80. WantedBy=multi-user.target
  81. # 启动Node Exporter服务
  82. sudo systemctl daemon-reload
  83. sudo systemctl start node_exporter
  84. sudo systemctl enable node_exporter
  85. # 检查Node Exporter状态
  86. sudo systemctl status node_exporter
  87. # 配置防火墙允许Prometheus和Node Exporter端口
  88. sudo firewall-cmd --permanent --add-port=9090/tcp
  89. sudo firewall-cmd --permanent --add-port=9100/tcp
  90. sudo firewall-cmd --reload
  91. # 安装Grafana
  92. sudo dnf install -y grafana
  93. # 启动并启用Grafana
  94. sudo systemctl start grafana-server
  95. sudo systemctl enable grafana-server
  96. # 检查Grafana状态
  97. sudo systemctl status grafana-server
  98. # 配置防火墙允许Grafana端口
  99. sudo firewall-cmd --permanent --add-port=3000/tcp
  100. sudo firewall-cmd --reload
  101. # 访问Grafana
  102. # http://<server_ip_or_name>:3000
  103. # 默认用户名和密码: admin/admin
复制代码

8. 性能优化

8.1 系统性能调优
  1. # 查看CPU信息
  2. lscpu
  3. # 查看CPU使用率
  4. top
  5. htop
  6. # 设置CPU性能模式
  7. sudo cpupower frequency-set -g performance
  8. # 查看CPU频率
  9. cpupower frequency-info
  10. # 安装tuned并选择性能配置文件
  11. sudo dnf install tuned -y
  12. sudo systemctl start tuned
  13. sudo systemctl enable tuned
  14. # 查看可用的配置文件
  15. sudo tuned-adm list
  16. # 应用性能配置文件
  17. sudo tuned-adm profile throughput-performance
  18. # 查看当前活动的配置文件
  19. sudo tuned-adm active
复制代码
  1. # 查看内存使用情况
  2. free -h
  3. vmstat -s
  4. # 查看内存详细信息
  5. cat /proc/meminfo
  6. # 创建交换文件(如果需要)
  7. sudo fallocate -l 2G /swapfile
  8. sudo chmod 600 /swapfile
  9. sudo mkswap /swapfile
  10. sudo swapon /swapfile
  11. echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
  12. # 调整swappiness参数
  13. echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
  14. sudo sysctl -p
  15. # 清理缓存
  16. sudo sync; echo 1 > /proc/sys/vm/drop_caches  # 清理页缓存
  17. sudo sync; echo 2 > /proc/sys/vm/drop_caches  # 清理目录项和inode缓存
  18. sudo sync; echo 3 > /proc/sys/vm/drop_caches  # 清理页缓存、目录项和inode缓存
复制代码
  1. # 查看磁盘I/O统计
  2. iostat -xz 1
  3. # 查看磁盘使用情况
  4. df -h
  5. # 查看磁盘I/O调度器
  6. cat /sys/block/sda/queue/scheduler
  7. # 设置I/O调度器为deadline
  8. echo deadline | sudo tee /sys/block/sda/queue/scheduler
  9. # 永久设置I/O调度器
  10. echo 'echo deadline > /sys/block/sda/queue/scheduler' | sudo tee -a /etc/rc.local
  11. sudo chmod +x /etc/rc.local
  12. # 查看磁盘读写速度
  13. sudo hdparm -Tt /dev/sda
  14. # 使用fio进行磁盘性能测试
  15. sudo dnf install fio -y
  16. # 顺序读写测试
  17. fio --name=seqread --ioengine=libaio --direct=1 --bs=1M --size=1G --rw=read --filename=/tmp/testfile --runtime=60 --time_based=1 --group_reporting
  18. fio --name=seqwrite --ioengine=libaio --direct=1 --bs=1M --size=1G --rw=write --filename=/tmp/testfile --runtime=60 --time_based=1 --group_reporting
  19. # 随机读写测试
  20. fio --name=randread --ioengine=libaio --direct=1 --bs=4k --size=1G --rw=randread --filename=/tmp/testfile --runtime=60 --time_based=1 --group_reporting
  21. fio --name=randwrite --ioengine=libaio --direct=1 --bs=4k --size=1G --rw=randwrite --filename=/tmp/testfile --runtime=60 --time_based=1 --group_reporting
复制代码

8.2 应用性能优化
  1. # 编辑Nginx主配置文件
  2. sudo vi /etc/nginx/nginx.conf
  3. # 优化worker进程和连接数
  4. worker_processes auto;  # 设置为auto会自动检测CPU核心数
  5. worker_rlimit_nofile 65535;  # 增加文件描述符限制
  6. events {
  7.     worker_connections 65535;  # 每个worker进程的最大连接数
  8.     multi_accept on;  # 允许一个worker进程同时接受多个新连接
  9.     use epoll;  # 使用高效的epoll事件模型
  10. }
  11. # 优化HTTP设置
  12. http {
  13.     sendfile on;  # 使用sendfile系统调用来传输文件
  14.     tcp_nopush on;  # 优化sendfile
  15.     tcp_nodelay on;  # 禁用Nagle算法,减少延迟
  16.    
  17.     keepalive_timeout 30;  # 保持连接的超时时间
  18.     keepalive_requests 1000;  # 单个连接可以处理的最大请求数
  19.    
  20.     client_body_timeout 10;  # 客户端请求体读取超时时间
  21.     client_header_timeout 10;  # 客户端请求头读取超时时间
  22.     send_timeout 2;  # 发送响应的超时时间
  23.    
  24.     client_max_body_size 20m;  # 客户端请求体的最大大小
  25.     client_body_buffer_size 128k;  # 客户端请求体的缓冲区大小
  26.    
  27.     # 开启Gzip压缩
  28.     gzip on;
  29.     gzip_vary on;
  30.     gzip_min_length 1024;
  31.     gzip_proxied expired no-cache no-store private auth;
  32.     gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
  33.    
  34.     # 配置缓存
  35.     open_file_cache max=200000 inactive=20s;
  36.     open_file_cache_valid 30s;
  37.     open_file_cache_min_uses 2;
  38.     open_file_cache_errors on;
  39. }
  40. # 测试Nginx配置
  41. sudo nginx -t
  42. # 重新加载Nginx配置
  43. sudo systemctl reload nginx
复制代码
  1. # 编辑MySQL/MariaDB配置文件
  2. sudo vi /etc/my.cnf.d/mariadb-server.cnf
  3. # 添加或修改以下配置:
  4. [mysqld]
  5. # 基本设置
  6. character-set-server = utf8mb4
  7. collation-server = utf8mb4_unicode_ci
  8. default-storage-engine = InnoDB
  9. # 内存设置
  10. innodb_buffer_pool_size = 4G  # 设置为系统内存的50-70%
  11. innodb_buffer_pool_instances = 4  # 设置为CPU核心数或更少
  12. innodb_log_file_size = 512M
  13. innodb_log_buffer_size = 64M
  14. query_cache_type = 0  # 在MySQL 8.0和MariaDB 10.4+中已移除查询缓存
  15. query_cache_size = 0  # 在MySQL 8.0和MariaDB 10.4+中已移除查询缓存
  16. # 连接设置
  17. max_connections = 500
  18. max_connect_errors = 100000
  19. thread_cache_size = 100
  20. thread_stack = 192K
  21. # InnoDB设置
  22. innodb_file_per_table = 1
  23. innodb_flush_log_at_trx_commit = 2  # 在性能和数据安全之间取得平衡
  24. innodb_flush_method = O_DIRECT
  25. innodb_read_io_threads = 8
  26. innodb_write_io_threads = 8
  27. innodb_thread_concurrency = 0
  28. # 日志设置
  29. slow_query_log = 1
  30. slow_query_log_file = /var/log/mariadb/slow.log
  31. long_query_time = 2
  32. log_queries_not_using_indexes = 1
  33. # 其他设置
  34. tmp_table_size = 64M
  35. max_heap_table_size = 64M
  36. sort_buffer_size = 2M
  37. read_buffer_size = 1M
  38. read_rnd_buffer_size = 2M
  39. join_buffer_size = 2M
  40. table_open_cache = 2000
  41. table_definition_cache = 2000
  42. # 重启MySQL/MariaDB服务
  43. sudo systemctl restart mariadb
  44. # 检查MySQL/MariaDB状态
  45. sudo systemctl status mariadb
  46. # 使用mysqltuner进行性能分析
  47. # 安装mysqltuner
  48. wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl
  49. chmod +x mysqltuner.pl
  50. # 运行mysqltuner
  51. ./mysqltuner.pl
复制代码
  1. # 编辑PHP配置文件
  2. sudo vi /etc/php.ini
  3. # 优化以下配置:
  4. memory_limit = 256M
  5. max_execution_time = 30
  6. max_input_time = 60
  7. upload_max_filesize = 20M
  8. post_max_size = 20M
  9. max_input_vars = 3000
  10. # 编辑PHP-FPM配置文件
  11. sudo vi /etc/php-fpm.d/www.conf
  12. # 优化以下配置:
  13. pm = dynamic
  14. pm.max_children = 100
  15. pm.start_servers = 20
  16. pm.min_spare_servers = 10
  17. pm.max_spare_servers = 30
  18. pm.max_requests = 1000
  19. request_terminate_timeout = 30
  20. # 编辑OPcache配置
  21. sudo vi /etc/php.d/10-opcache.ini
  22. # 优化以下配置:
  23. opcache.enable=1
  24. opcache.memory_consumption=128
  25. opcache.interned_strings_buffer=8
  26. opcache.max_accelerated_files=4000
  27. opcache.revalidate_freq=2
  28. opcache.fast_shutdown=1
  29. # 重启PHP-FPM服务
  30. sudo systemctl restart php-fpm
  31. # 检查PHP-FPM状态
  32. sudo systemctl status php-fpm
复制代码

9. 故障排除与常见问题解决

9.1 系统启动问题
  1. # 查看系统日志
  2. sudo journalctl -xb
  3. # 检查磁盘空间
  4. df -h
  5. # 检查文件系统
  6. sudo fsck -f /dev/sda1
  7. # 检查引导加载程序
  8. sudo grub2-mkconfig -o /boot/grub2/grub.cfg
  9. # 修复引导加载程序
  10. sudo grub2-install /dev/sda
  11. # 检查系统服务状态
  12. sudo systemctl list-units --type=service --state=failed
  13. # 重启系统
  14. sudo reboot
复制代码
  1. # 查看服务状态
  2. sudo systemctl status service_name
  3. # 查看服务日志
  4. sudo journalctl -u service_name
  5. # 检查服务配置文件
  6. sudo vi /etc/systemd/system/service_name.service
  7. # 重新加载systemd配置
  8. sudo systemctl daemon-reload
  9. # 重启服务
  10. sudo systemctl restart service_name
  11. # 检查服务依赖
  12. sudo systemctl list-dependencies service_name
复制代码

9.2 网络问题
  1. # 检查网络接口
  2. ip addr show
  3. # 检查网络连接
  4. ping -c 4 8.8.8.8
  5. # 检查DNS解析
  6. nslookup example.com
  7. # 检查路由表
  8. ip route show
  9. # 检查网络服务状态
  10. sudo systemctl status NetworkManager
  11. # 重启网络服务
  12. sudo systemctl restart NetworkManager
  13. # 检查防火墙状态
  14. sudo firewall-cmd --state
  15. # 检查SELinux状态
  16. getenforce
  17. # 检查网络配置文件
  18. sudo vi /etc/sysconfig/network-scripts/ifcfg-eth0
复制代码
  1. # 检查端口是否监听
  2. sudo ss -tulnp | grep :port_number
  3. # 检查防火墙规则
  4. sudo firewall-cmd --list-all
  5. # 检查SELinux策略
  6. sudo semanage port -l | grep port_number
  7. # 添加防火墙规则
  8. sudo firewall-cmd --permanent --add-port=port_number/tcp
  9. sudo firewall-cmd --reload
  10. # 添加SELinux端口策略
  11. sudo semanage port -a -t http_port_t -p tcp port_number
  12. # 检查服务状态
  13. sudo systemctl status service_name
  14. # 检查服务配置
  15. sudo vi /etc/service_name/service_name.conf
复制代码

9.3 性能问题
  1. # 查看系统负载
  2. uptime
  3. top
  4. htop
  5. # 查看CPU使用率
  6. mpstat -P ALL 1
  7. # 查看内存使用情况
  8. free -h
  9. vmstat 1
  10. # 查看磁盘I/O
  11. iostat -xz 1
  12. # 查看网络连接
  13. ss -tulnp
  14. # 查看进程资源使用情况
  15. ps aux --sort=-%cpu | head
  16. ps aux --sort=-%mem | head
  17. # 查看系统日志
  18. sudo journalctl -f
  19. # 查看内核日志
  20. dmesg -T | tail
  21. # 查看系统资源限制
  22. ulimit -a
复制代码
  1. # 查看磁盘使用情况
  2. df -h
  3. # 查看目录大小
  4. du -sh /path/to/directory
  5. # 查看大文件
  6. find /path/to/search -type f -size +100M -exec ls -lh {} \;
  7. # 清理软件包缓存
  8. sudo dnf clean all
  9. # 清理日志文件
  10. sudo journalctl --vacuum-size=100M
  11. # 清理临时文件
  12. sudo rm -rf /tmp/*
  13. # 查找并删除旧的日志文件
  14. sudo find /var/log -type f -name "*.log.*" -delete
  15. # 查找并删除核心转储文件
  16. sudo find /var/crash -type f -delete
  17. # 查找并删除旧的备份文件
  18. sudo find /backup -type f -mtime +30 -delete
复制代码

9.4 安全问题
  1. # 检查异常登录
  2. sudo lastb
  3. sudo last
  4. # 检查异常进程
  5. ps aux
  6. # 检查网络连接
  7. sudo ss -tulnp
  8. # 检查计划任务
  9. crontab -l
  10. sudo cat /etc/crontab
  11. sudo ls /etc/cron.d/
  12. # 检查系统服务
  13. sudo systemctl list-units --type=service
  14. # 检查用户账户
  15. sudo cat /etc/passwd
  16. sudo cat /etc/shadow
  17. # 检查sudo权限
  18. sudo cat /etc/sudoers
  19. # 检查SSH配置
  20. sudo cat /etc/ssh/sshd_config
  21. # 检查防火墙规则
  22. sudo firewall-cmd --list-all
  23. # 检查SELinux状态
  24. getenforce
  25. # 安装并运行安全扫描工具
  26. sudo dnf install rkhunter -y
  27. sudo rkhunter --checkall
  28. # 安装并运行恶意软件扫描工具
  29. sudo dnf install clamav -y
  30. sudo freshclam
  31. sudo clamscan -r --infected /home
复制代码
  1. # 检查网络连接
  2. sudo ss -tulnp
  3. # 检查网络流量
  4. sudo iftop -nNP
  5. # 检查系统负载
  6. uptime
  7. top
  8. # 检查Web服务器访问日志
  9. sudo tail -f /var/log/nginx/access.log
  10. sudo tail -f /var/log/httpd/access_log
  11. # 使用fail2ban阻止恶意IP
  12. sudo fail2ban-client status sshd
  13. sudo fail2ban-client set sshd banip IP_ADDRESS
  14. # 使用iptables阻止恶意IP
  15. sudo iptables -A INPUT -s IP_ADDRESS -j DROP
  16. # 使用firewalld阻止恶意IP
  17. sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="IP_ADDRESS" drop'
  18. sudo firewall-cmd --reload
  19. # 配置连接限制
  20. sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 100 -j DROP
  21. # 配置速率限制
  22. sudo iptables -A INPUT -p tcp --dport 80 -m limit --limit 50/minute --limit-burst 100 -j ACCEPT
  23. sudo iptables -A INPUT -p tcp --dport 80 -j DROP
  24. # 使用DDoS防护工具
  25. sudo dnf install fail2ban -y
  26. sudo systemctl start fail2ban
  27. sudo systemctl enable fail2ban
复制代码

10. 高级主题

10.1 集群部署
  1. # 安装Keepalived
  2. sudo dnf install keepalived -y
  3. # 在主节点上配置Keepalived
  4. sudo vi /etc/keepalived/keepalived.conf
  5. # 添加以下配置:
  6. vrrp_script chk_nginx {
  7.     script "killall -0 nginx"
  8.     interval 2
  9.     weight 2
  10. }
  11. vrrp_instance VI_1 {
  12.     state MASTER
  13.     interface eth0
  14.     virtual_router_id 51
  15.     priority 101
  16.     advert_int 1
  17.     authentication {
  18.         auth_type PASS
  19.         auth_pass your_password
  20.     }
  21.     virtual_ipaddress {
  22.         192.168.1.100/24 dev eth0
  23.     }
  24.     track_script {
  25.         chk_nginx
  26.     }
  27. }
  28. # 在备用节点上配置Keepalived
  29. sudo vi /etc/keepalived/keepalived.conf
  30. # 添加以下配置:
  31. vrrp_script chk_nginx {
  32.     script "killall -0 nginx"
  33.     interval 2
  34.     weight 2
  35. }
  36. vrrp_instance VI_1 {
  37.     state BACKUP
  38.     interface eth0
  39.     virtual_router_id 51
  40.     priority 100
  41.     advert_int 1
  42.     authentication {
  43.         auth_type PASS
  44.         auth_pass your_password
  45.     }
  46.     virtual_ipaddress {
  47.         192.168.1.100/24 dev eth0
  48.     }
  49.     track_script {
  50.         chk_nginx
  51.     }
  52. }
  53. # 启动并启用Keepalived
  54. sudo systemctl start keepalived
  55. sudo systemctl enable keepalived
  56. # 检查Keepalived状态
  57. sudo systemctl status keepalived
  58. # 检查虚拟IP
  59. ip addr show
  60. # 配置防火墙允许VRRP协议
  61. sudo firewall-cmd --permanent --add-rich-rule='rule protocol value="vrrp" accept'
  62. sudo firewall-cmd --reload
复制代码
  1. # 安装HAProxy
  2. sudo dnf install haproxy -y
  3. # 配置HAProxy
  4. sudo vi /etc/haproxy/haproxy.cfg
  5. # 添加以下配置:
  6. global
  7.     log         127.0.0.1 local2
  8.     chroot      /var/lib/haproxy
  9.     pidfile     /var/run/haproxy.pid
  10.     maxconn     4000
  11.     user        haproxy
  12.     group       haproxy
  13.     daemon
  14.     stats socket /var/lib/haproxy/stats
  15. defaults
  16.     mode                    http
  17.     log                     global
  18.     option                  httplog
  19.     option                  dontlognull
  20.     option http-server-close
  21.     option forwardfor       except 127.0.0.0/8
  22.     option                  redispatch
  23.     retries                 3
  24.     timeout http-request    10s
  25.     timeout queue           1m
  26.     timeout connect         10s
  27.     timeout client          1m
  28.     timeout server          1m
  29.     timeout http-keep-alive 10s
  30.     timeout check           10s
  31.     maxconn                 3000
  32. frontend main
  33.     bind *:80
  34.     acl url_static       path_beg       -i /static /images /javascript /stylesheets
  35.     acl url_static       path_end       -i .jpg .gif .png .css .js
  36.     use_backend static          if url_static
  37.     default_backend             app
  38. backend static
  39.     balance     roundrobin
  40.     server      static 127.0.0.1:4331 check
  41. backend app
  42.     balance     roundrobin
  43.     server  app1 192.168.1.11:80 check
  44.     server  app2 192.168.1.12:80 check
  45. listen stats
  46.     bind *:8404
  47.     stats enable
  48.     stats uri /stats
  49.     stats refresh 30s
  50.     stats auth admin:your_password
  51.     stats hide-version
  52. # 启动并启用HAProxy
  53. sudo systemctl start haproxy
  54. sudo systemctl enable haproxy
  55. # 检查HAProxy状态
  56. sudo systemctl status haproxy
  57. # 配置防火墙允许HAProxy端口
  58. sudo firewall-cmd --permanent --add-port=80/tcp
  59. sudo firewall-cmd --permanent --add-port=8404/tcp
  60. sudo firewall-cmd --reload
  61. # 访问HAProxy统计页面
  62. # http://<haproxy_ip>:8404/stats
复制代码

10.2 容器化部署
  1. # 创建项目目录
  2. mkdir myapp && cd myapp
  3. # 创建Dockerfile
  4. vi Dockerfile
  5. # 添加以下内容:
  6. FROM rockylinux:9
  7. RUN dnf install -y nginx
  8. COPY index.html /usr/share/nginx/html/
  9. EXPOSE 80
  10. CMD ["nginx", "-g", "daemon off;"]
  11. # 创建index.html
  12. vi index.html
  13. # 添加以下内容:
  14. <!DOCTYPE html>
  15. <html>
  16. <head>
  17.     <title>Welcome to My App!</title>
  18. </head>
  19. <body>
  20.     <h1>Hello from Docker!</h1>
  21. </body>
  22. </html>
  23. # 创建docker-compose.yml
  24. vi docker-compose.yml
  25. # 添加以下内容:
  26. version: '3'
  27. services:
  28.   web:
  29.     build: .
  30.     ports:
  31.       - "80:80"
  32.     volumes:
  33.       - ./nginx.conf:/etc/nginx/nginx.conf:ro
  34.     depends_on:
  35.       - db
  36.     networks:
  37.       - app-network
  38.   db:
  39.     image: mariadb:10.5
  40.     environment:
  41.       MYSQL_ROOT_PASSWORD: example
  42.       MYSQL_DATABASE: myapp
  43.       MYSQL_USER: myapp
  44.       MYSQL_PASSWORD: myapp
  45.     volumes:
  46.       - db-data:/var/lib/mysql
  47.     networks:
  48.       - app-network
  49. volumes:
  50.   db-data:
  51. networks:
  52.   app-network:
  53.     driver: bridge
  54. # 创建nginx.conf
  55. vi nginx.conf
  56. # 添加以下内容:
  57. events {
  58.     worker_connections 1024;
  59. }
  60. http {
  61.     server {
  62.         listen 80;
  63.         server_name localhost;
  64.         location / {
  65.             root /usr/share/nginx/html;
  66.             index index.html;
  67.         }
  68.     }
  69. }
  70. # 启动应用
  71. docker-compose up -d
  72. # 查看容器状态
  73. docker-compose ps
  74. # 查看应用日志
  75. docker-compose logs
  76. # 停止应用
  77. docker-compose down
  78. # 清理资源
  79. docker-compose down -v
复制代码
  1. # 安装Kubernetes工具
  2. sudo dnf install -y kubectl
  3. # 安装Minikube(用于本地测试)
  4. curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
  5. sudo install minikube-linux-amd64 /usr/local/bin/minikube
  6. # 启动Minikube集群
  7. minikube start --driver=docker
  8. # 检查集群状态
  9. kubectl cluster-info
  10. kubectl get nodes
  11. # 创建部署配置文件
  12. vi deployment.yaml
  13. # 添加以下内容:
  14. apiVersion: apps/v1
  15. kind: Deployment
  16. metadata:
  17.   name: myapp
  18. spec:
  19.   replicas: 3
  20.   selector:
  21.     matchLabels:
  22.       app: myapp
  23.   template:
  24.     metadata:
  25.       labels:
  26.         app: myapp
  27.     spec:
  28.       containers:
  29.       - name: myapp
  30.         image: rockylinux:9
  31.         command: ["/bin/sh", "-c", "dnf install -y nginx && echo 'Hello from Kubernetes!' > /usr/share/nginx/html/index.html && nginx -g 'daemon off;'"]
  32.         ports:
  33.         - containerPort: 80
  34. # 创建服务配置文件
  35. vi service.yaml
  36. # 添加以下内容:
  37. apiVersion: v1
  38. kind: Service
  39. metadata:
  40.   name: myapp-service
  41. spec:
  42.   selector:
  43.     app: myapp
  44.   ports:
  45.     - protocol: TCP
  46.       port: 80
  47.       targetPort: 80
  48.   type: LoadBalancer
  49. # 部署应用
  50. kubectl apply -f deployment.yaml
  51. kubectl apply -f service.yaml
  52. # 查看部署状态
  53. kubectl get deployments
  54. kubectl get pods
  55. kubectl get services
  56. # 访问应用
  57. minikube service myapp-service
  58. # 扩展应用
  59. kubectl scale deployment myapp --replicas=5
  60. # 查看扩展后的状态
  61. kubectl get deployments
  62. kubectl get pods
  63. # 清理资源
  64. kubectl delete service myapp-service
  65. kubectl delete deployment myapp
复制代码

10.3 自动化部署
  1. # 安装Ansible
  2. sudo dnf install ansible -y
  3. # 创建Ansible配置文件
  4. mkdir -p ~/ansible && cd ~/ansible
  5. vi ansible.cfg
  6. # 添加以下内容:
  7. [defaults]
  8. inventory = inventory
  9. host_key_checking = False
  10. remote_user = adminuser
  11. ask_pass = False
  12. private_key_file = ~/.ssh/rocky-cloud-key
  13. # 创建主机清单文件
  14. vi inventory
  15. # 添加以下内容:
  16. [webservers]
  17. web1 ansible_host=192.168.1.11
  18. web2 ansible_host=192.168.1.12
  19. [dbservers]
  20. db1 ansible_host=192.168.1.21
  21. [all:vars]
  22. ansible_python_interpreter=/usr/bin/python3
  23. # 创建Playbook文件
  24. vi deploy_webserver.yml
  25. # 添加以下内容:
  26. ---
  27. - name: Deploy web server
  28.   hosts: webservers
  29.   become: yes
  30.   
  31.   tasks:
  32.     - name: Install EPEL repository
  33.       dnf:
  34.         name: epel-release
  35.         state: present
  36.    
  37.     - name: Install nginx
  38.       dnf:
  39.         name: nginx
  40.         state: present
  41.    
  42.     - name: Start and enable nginx
  43.       systemd:
  44.         name: nginx
  45.         state: started
  46.         enabled: yes
  47.    
  48.     - name: Create website directory
  49.       file:
  50.         path: /var/www/example.com/html
  51.         state: directory
  52.         owner: nginx
  53.         group: nginx
  54.         mode: '0755'
  55.    
  56.     - name: Copy website content
  57.       copy:
  58.         content: |
  59.           <!DOCTYPE html>
  60.           <html>
  61.           <head>
  62.               <title>Welcome to Example.com!</title>
  63.           </head>
  64.           <body>
  65.               <h1>Success! The Nginx server is working!</h1>
  66.           </body>
  67.           </html>
  68.         dest: /var/www/example.com/html/index.html
  69.         owner: nginx
  70.         group: nginx
  71.         mode: '0644'
  72.    
  73.     - name: Copy nginx configuration
  74.       copy:
  75.         content: |
  76.           server {
  77.               listen 80;
  78.               server_name example.com www.example.com;
  79.               root /var/www/example.com/html;
  80.               index index.html;
  81.               
  82.               location / {
  83.                   try_files $uri $uri/ =404;
  84.               }
  85.               
  86.               error_page 404 /404.html;
  87.               error_page 500 502 503 504 /50x.html;
  88.               location = /50x.html {
  89.                   root /usr/share/nginx/html;
  90.               }
  91.           }
  92.         dest: /etc/nginx/conf.d/example.com.conf
  93.         owner: root
  94.         group: root
  95.         mode: '0644'
  96.         validate: /usr/sbin/nginx -t -c %s
  97.    
  98.     - name: Restart nginx
  99.       systemd:
  100.         name: nginx
  101.         state: restarted
  102.    
  103.     - name: Open firewall port
  104.       firewalld:
  105.         service: http
  106.         permanent: yes
  107.         state: enabled
  108.         immediate: yes
  109. # 运行Playbook
  110. ansible-playbook deploy_webserver.yml
  111. # 检查执行结果
  112. ansible webservers -m uri -a "url=http://localhost"
复制代码
  1. # 安装Java
  2. sudo dnf install java-11-openjdk -y
  3. # 添加Jenkins仓库
  4. sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
  5. sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
  6. # 安装Jenkins
  7. sudo dnf install jenkins -y
  8. # 启动并启用Jenkins
  9. sudo systemctl start jenkins
  10. sudo systemctl enable jenkins
  11. # 检查Jenkins状态
  12. sudo systemctl status jenkins
  13. # 配置防火墙允许Jenkins端口
  14. sudo firewall-cmd --permanent --add-port=8080/tcp
  15. sudo firewall-cmd --reload
  16. # 获取初始管理员密码
  17. sudo cat /var/lib/jenkins/secrets/initialAdminPassword
  18. # 访问Jenkins
  19. # http://<server_ip>:8080
  20. # 安装必要的插件
  21. # 在Jenkins Web界面中,安装以下插件:
  22. # - Git Plugin
  23. # - Pipeline Plugin
  24. # - Docker Plugin
  25. # - Ansible Plugin
  26. # 创建Jenkinsfile
  27. vi Jenkinsfile
  28. # 添加以下内容:
  29. pipeline {
  30.     agent any
  31.    
  32.     stages {
  33.         stage('Checkout') {
  34.             steps {
  35.                 git 'https://github.com/yourusername/yourrepository.git'
  36.             }
  37.         }
  38.         
  39.         stage('Build') {
  40.             steps {
  41.                 sh 'docker build -t yourapp:latest .'
  42.             }
  43.         }
  44.         
  45.         stage('Test') {
  46.             steps {
  47.                 sh 'docker run --rm yourapp:latest /bin/sh -c "npm test"'
  48.             }
  49.         }
  50.         
  51.         stage('Deploy') {
  52.             steps {
  53.                 ansiblePlaybook(
  54.                     playbook: 'deploy.yml',
  55.                     inventory: 'inventory',
  56.                     credentialsId: 'ansible-ssh-key'
  57.                 )
  58.             }
  59.         }
  60.     }
  61.    
  62.     post {
  63.         always {
  64.             echo 'Pipeline completed'
  65.             cleanWs()
  66.         }
  67.     }
  68. }
  69. # 创建Ansible部署文件
  70. vi deploy.yml
  71. # 添加以下内容:
  72. ---
  73. - name: Deploy application
  74.   hosts: webservers
  75.   become: yes
  76.   
  77.   tasks:
  78.     - name: Pull latest Docker image
  79.       docker_image:
  80.         name: yourapp
  81.         tag: latest
  82.         source: pull
  83.    
  84.     - name: Stop existing container
  85.       docker_container:
  86.         name: yourapp
  87.         state: stopped
  88.       ignore_errors: yes
  89.    
  90.     - name: Remove existing container
  91.       docker_container:
  92.         name: yourapp
  93.         state: absent
  94.       ignore_errors: yes
  95.    
  96.     - name: Start new container
  97.       docker_container:
  98.         name: yourapp
  99.         image: yourapp:latest
  100.         state: started
  101.         ports:
  102.           - "80:80"
  103.         restart_policy: always
复制代码

11. 总结与最佳实践

11.1 Rocky Linux云服务部署最佳实践

1. 系统安全始终保持系统更新:sudo dnf update -y配置防火墙:只开放必要的端口启用SELinux:sudo setenforce 1禁用root远程登录:PermitRootLogin no使用SSH密钥认证:PasswordAuthentication no安装fail2ban防止暴力破解
2. 始终保持系统更新:sudo dnf update -y
3. 配置防火墙:只开放必要的端口
4. 启用SELinux:sudo setenforce 1
5. 禁用root远程登录:PermitRootLogin no
6. 使用SSH密钥认证:PasswordAuthentication no
7. 安装fail2ban防止暴力破解
8. 系统性能根据服务器用途调整内核参数优化文件系统:使用noatime选项配置适当的资源限制使用性能分析工具监控系统状态定期清理日志和临时文件
9. 根据服务器用途调整内核参数
10. 优化文件系统:使用noatime选项
11. 配置适当的资源限制
12. 使用性能分析工具监控系统状态
13. 定期清理日志和临时文件
14. 服务配置使用最小化安装原则只安装必要的服务和软件包为每个服务创建专用用户配置适当的资源限制定期备份配置文件
15. 使用最小化安装原则
16. 只安装必要的服务和软件包
17. 为每个服务创建专用用户
18. 配置适当的资源限制
19. 定期备份配置文件
20. 监控与维护部署监控系统(如Zabbix、Prometheus)配置日志轮转设置告警机制定期检查系统健康状态制定灾难恢复计划
21. 部署监控系统(如Zabbix、Prometheus)
22. 配置日志轮转
23. 设置告警机制
24. 定期检查系统健康状态
25. 制定灾难恢复计划
26. 高可用与扩展使用负载均衡器分发流量配置高可用集群实施自动扩展策略使用容器化技术简化部署实施CI/CD流程自动化部署
27. 使用负载均衡器分发流量
28. 配置高可用集群
29. 实施自动扩展策略
30. 使用容器化技术简化部署
31. 实施CI/CD流程自动化部署

系统安全

• 始终保持系统更新:sudo dnf update -y
• 配置防火墙:只开放必要的端口
• 启用SELinux:sudo setenforce 1
• 禁用root远程登录:PermitRootLogin no
• 使用SSH密钥认证:PasswordAuthentication no
• 安装fail2ban防止暴力破解

系统性能

• 根据服务器用途调整内核参数
• 优化文件系统:使用noatime选项
• 配置适当的资源限制
• 使用性能分析工具监控系统状态
• 定期清理日志和临时文件

服务配置

• 使用最小化安装原则
• 只安装必要的服务和软件包
• 为每个服务创建专用用户
• 配置适当的资源限制
• 定期备份配置文件

监控与维护

• 部署监控系统(如Zabbix、Prometheus)
• 配置日志轮转
• 设置告警机制
• 定期检查系统健康状态
• 制定灾难恢复计划

高可用与扩展

• 使用负载均衡器分发流量
• 配置高可用集群
• 实施自动扩展策略
• 使用容器化技术简化部署
• 实施CI/CD流程自动化部署

11.2 常见问题解决方案

1. 系统更新失败“`bash清理DNF缓存sudo dnf clean all

系统更新失败“`bash

sudo dnf clean all

# 重建RPM数据库
   sudo rpm –rebuilddb

# 尝试再次更新
   sudo dnf update -y
  1. 2. **磁盘空间不足**
  2.    ```bash
  3.    # 查找大文件
  4.    sudo find / -type f -size +100M -exec ls -lh {} \;
  5.    
  6.    # 清理软件包缓存
  7.    sudo dnf clean all
  8.    
  9.    # 清理日志文件
  10.    sudo journalctl --vacuum-size=100M
复制代码

1. 服务无法启动“`bash检查服务状态sudo systemctl status service_name

服务无法启动“`bash

sudo systemctl status service_name

# 查看服务日志
   sudo journalctl -u service_name

# 检查配置文件语法
   sudo service_name configtest
  1. 4. **网络连接问题**
  2.    ```bash
  3.    # 检查网络接口
  4.    ip addr show
  5.    
  6.    # 检查路由表
  7.    ip route show
  8.    
  9.    # 检查DNS解析
  10.    nslookup example.com
  11.    
  12.    # 检查防火墙规则
  13.    sudo firewall-cmd --list-all
复制代码

1. 性能问题“`bash查看系统负载uptime

性能问题“`bash

uptime

# 查看CPU使用率
   top

# 查看内存使用情况
   free -h

# 查看磁盘I/O
   iostat -xz 1
   “`

11.3 未来发展趋势

1. 云原生技术容器化部署将成为主流Kubernetes将成为容器编排的标准微服务架构将更加普及无服务器计算(Serverless)将得到更广泛应用
2. 容器化部署将成为主流
3. Kubernetes将成为容器编排的标准
4. 微服务架构将更加普及
5. 无服务器计算(Serverless)将得到更广泛应用
6. 自动化与智能化AI驱动的运维自动化智能故障预测与自愈系统自动化安全防护智能资源调度与优化
7. AI驱动的运维自动化
8. 智能故障预测与自愈系统
9. 自动化安全防护
10. 智能资源调度与优化
11. 安全与合规零信任安全模型自动化合规检查增强的数据保护机制更严格的访问控制
12. 零信任安全模型
13. 自动化合规检查
14. 增强的数据保护机制
15. 更严格的访问控制
16. 边缘计算分布式云架构边缘节点部署低延迟应用优化边缘-云协同计算
17. 分布式云架构
18. 边缘节点部署
19. 低延迟应用优化
20. 边缘-云协同计算

云原生技术

• 容器化部署将成为主流
• Kubernetes将成为容器编排的标准
• 微服务架构将更加普及
• 无服务器计算(Serverless)将得到更广泛应用

自动化与智能化

• AI驱动的运维自动化
• 智能故障预测与自愈系统
• 自动化安全防护
• 智能资源调度与优化

安全与合规

• 零信任安全模型
• 自动化合规检查
• 增强的数据保护机制
• 更严格的访问控制

边缘计算

• 分布式云架构
• 边缘节点部署
• 低延迟应用优化
• 边缘-云协同计算

通过本文的详细介绍,您应该已经掌握了Rocky Linux云服务搭建的完整流程与实用技巧。从基础知识到高级主题,从系统安装到性能优化,从单机部署到集群架构,我们全面覆盖了Rocky Linux在云端部署的各个方面。希望这些内容能够帮助您在实际应用中解决问题,提升系统稳定性与安全性,为企业级应用提供可靠的基础设施支持。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则