如何在Debian上配置服务器
小樊
41
2025-12-01 11:10:23
Debian 服务器配置全流程
一 基础准备与系统更新
- 选择 Debian Stable 作为长期运行版本,稳定性与安全性更好。
- 更新索引并升级系统:
sudo apt update && sudo apt full-upgrade -y
sudo reboot
- 安装常用工具:
sudo apt install -y vim htop tmux curl wget unzip gnupg2 ca-certificates
- 建议启用自动安全更新:
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
以上步骤有助于保持系统处于最新安全补丁状态,降低风险。
二 网络与主机名配置
- 查看网卡名称:ip -br link(常见如 eth0、ens3、enp0s3)。
- 使用 /etc/network/interfaces 配置静态 IP(示例):
auto ens3
iface ens3 inet static
address 192.168.1.100/24
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
应用:sudo systemctl restart networking
- 使用 NetworkManager(适合桌面/混合环境):
sudo apt install -y network-manager
sudo systemctl enable --now NetworkManager
nmcli con mod “Wired connection 1” ipv4.addresses 192.168.1.100/24 ipv4.gateway 192.168.1.1 ipv4.dns “8.8.8.8 8.8.4.4” autoconnect yes
nmcli con up “Wired connection 1”
- 设置主机名与时区:
sudo hostnamectl set-hostname myserver
sudo timedatectl set-timezone Asia/Shanghai
- 故障排查:ip addr、ping 8.8.8.8、cat /etc/resolv.conf、tail -f /var/log/syslog
以上覆盖了常见的静态/动态 IP、NetworkManager 与基础排错路径。
三 防火墙与 SSH 安全
- UFW 快速策略(推荐):
sudo apt install -y ufw
sudo ufw allow 22/tcp
sudo ufw allow 80,443/tcp
sudo ufw enable
- 加固 SSH:
- 使用密钥登录,禁用口令与 root 远程登录。
- 编辑 /etc/ssh/sshd_config:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
- 重启服务:sudo systemctl restart ssh
- 入侵防护:
sudo apt install -y fail2ban
sudo systemctl enable --now fail2ban
以上措施可显著降低暴力破解与未授权访问风险。
四 部署 Web 环境二选一
- LAMP(Apache + MariaDB/MySQL + PHP)
- 安装:
sudo apt install -y apache2 mariadb-server php libapache2-mod-php php-mysql php-cli php-common php-curl php-gd php-json php-mbstring php-xml php-zip
sudo systemctl enable --now apache2 mariadb
- 数据库安全:sudo mysql_secure_installation
- 测试:echo “” | sudo tee /var/www/html/info.php
- 可选 phpMyAdmin:sudo apt install -y phpmyadmin(选择 Apache)
- LNMP(Nginx + MariaDB/MySQL + PHP-FPM)
- 安装:
sudo apt install -y nginx mariadb-server php-fpm php-mysql
sudo systemctl enable --now nginx mariadb php-fpm
- Nginx 处理 PHP(/etc/nginx/sites-available/default 片段):
index index.php index.html;
location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; }
location ~ /.ht { deny all; }
测试:echo “” | sudo tee /var/www/html/info.php
语法检查与重载:sudo nginx -t && sudo systemctl reload nginx
- PHP 建议:cgi.fix_pathinfo=0(/etc/php/7.4/fpm/php.ini)
以上步骤覆盖 LAMP 与 LNMP 的组件安装、基础安全与验证方法。
五 域名 HTTPS 与后续维护
- 申请并部署 Let’s Encrypt 证书(Apache 示例):
sudo apt install -y certbot python3-certbot-apache
sudo certbot --apache -d yourdomain.com
- 常用维护与加固
- 定期更新与补丁:sudo apt update && sudo apt full-upgrade -y
- 日志与监控:tail -f /var/log/syslog /var/log/apache2/error.log;资源监控用 htop
- 备份策略:对 /var/www、/etc、数据库进行周期性备份(如 tar/rsync)
- PHP 安全:在 php.ini 中限制危险函数(如 exec、system、shell_exec)与上传大小
- 数据库加固:仅允许本地访问、删除匿名账户、限制远程连接来源
这些操作可提升站点可靠性、合规性与可运维性。