Linux上线网站完整指南
1. 准备工作
在Linux系统上部署网站需要完成以下基础配置:
服务器选择:物理服务器、云服务器(VPS)或容器化部署
操作系统:推荐使用Ubuntu LTS、CentOS或Debian等稳定版本
网络配置:确保服务器有公网IP,防火墙开放必要端口(80,443,22等)
域名准备:注册域名并配置DNS解析
2. 环境安装与配置
2.1 Web服务器选择
常见Web服务器软件:
Apache:历史悠久,模块丰富
bash
# Ubuntu/Debian
sudo apt install apache2
# CentOS/RHEL
sudo yum install httpd
Nginx:高性能,反向代理能力强
bash
# Ubuntu/Debian
sudo apt install nginx
# CentOS/RHEL
sudo yum install nginx
2.2 数据库安装
MySQL/MariaDB:
bash
sudo apt install mariadb-server
sudo mysql_secure_installation
PostgreSQL:
bash
sudo apt install postgresql postgresql-contrib
2.3 编程语言环境
PHP:
bash
sudo apt install php php-mysql php-fpm
Python:
bash
sudo apt install python3 python3-pip python3-venv
Node.js:
bash
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt install nodejs
3. 网站部署流程
3.1 文件上传
SCP/SFTP:
bash
scp -r local_folder user@server_ip:/path/to/webroot
Git:
bash
git clone https://github.com/your/repo.git /var/www/your_site
Rsync:
bash
rsync -avz -e ssh local_folder user@server_ip:/path/to/webroot
3.2 权限配置
bash
sudo chown -R www-data:www-data /var/www/your_site
sudo chmod -R 755 /var/www/your_site
3.3 虚拟主机配置
Nginx示例:
nginx
server {
listen 80;
server_name yourdomain.com;
root /var/www/your_site;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
Apache示例:
apache
ServerName yourdomain.com
DocumentRoot /var/www/your_site
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
4. 安全加固
4.1 SSL证书配置
使用Let's Encrypt免费证书:
bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
4.2 防火墙配置
bash
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 22/tcp
sudo ufw enable
4.3 安全最佳实践
定期更新系统和软件包
禁用root远程登录
使用SSH密钥认证
配置fail2ban防止暴力破解
设置文件权限最小化原则
定期备份网站数据和数据库
5. 性能优化
5.1 Web服务器优化
Nginx:调整worker_processes、keepalive_timeout等参数
Apache:启用MPM事件模块,调整MaxRequestWorkers
5.2 缓存配置
浏览器缓存
服务器端缓存(OPcache, Redis, Memcached)
CDN加速
5.3 数据库优化
索引优化
查询缓存
定期维护表
6. 监控与维护
6.1 日志分析
配置日志轮转
使用工具分析访问日志(GoAccess, AWStats)
6.2 性能监控
top/htop查看系统资源
nginx-status/apache-status监控Web服务器
Prometheus + Grafana可视化监控
6.3 自动化部署
使用Ansible, Chef, Puppet配置管理
CI/CD流水线(GitLab CI, Jenkins)
容器化部署(Docker, Kubernetes)
7. 常见问题解决
403 Forbidden:检查文件权限和SELinux设置
502 Bad Gateway:检查PHP-FPM或后端服务状态
数据库连接失败:检查用户权限和防火墙设置
内存不足:优化应用或升级服务器配置
8. 进阶主题
负载均衡配置
高可用架构
微服务部署
无服务器架构(Serverless)
边缘计算部署
在Linux上部署网站是一个系统工程,需要根据实际业务需求选择合适的技术栈和架构方案。随着业务增长,可能需要进行架构演进和优化,建议从简单开始,逐步完善。网站上线后,持续的监控、维护和安全更新同样重要,这是确保网站长期稳定运行的关键。