服务器部署视频教程
# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
# CentOS
sudo yum update -y
创建新用户并分配权限(避免长期使用root账户):
adduser deployuser usermod -aG sudo deployuser # Ubuntu usermod -aG wheel deployuser # CentOS
步骤2:配置防火墙
-
开放必要端口(如HTTP 80、HTTPS 443、SSH 22):
# Ubuntu(UFW) sudo ufw allow 22/tcp sudo ufw enable # CentOS(Firewalld) sudo firewall-cmd --permanent --add-port=80/tcp sudo firewall-cmd --reload
步骤3:安装Web服务环境
-
以Nginx为例:
# Ubuntu sudo apt install nginx -y sudo systemctl start nginx # CentOS sudo yum install epel-release -y sudo yum install nginx -y sudo systemctl enable nginx
部署应用程序
场景1:静态网站部署
server {
listen 80;
server_name your_domain.com;
root /var/www/html;
index index.html;
}
sudo systemctl restart nginx
场景2:动态应用部署(以Node.js为例)
- 安装Node.js与PM2(进程管理工具):
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install nodejs -y sudo npm install pm2 -g
- 上传代码并安装依赖:
cd /path/to/app npm install pm2 start app.js
- 配置Nginx反向代理:
server { listen 80; server_name your_domain.com; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; } }
安全加固与监控
- SSL证书配置
- 使用Let’s Encrypt免费证书:
sudo apt install certbot python3-certbot-nginx -y sudo certbot --nginx -d your_domain.com
- 使用Let’s Encrypt免费证书:
- 定期备份数据
- 通过cron任务自动备份:
# 每天凌晨备份网站目录 0 0 * * * tar -czvf /backup/website_$(date +%F).tar.gz /var/www/html
- 通过cron任务自动备份:
- 安装监控工具
- 使用Prometheus+Grafana监控服务器性能。
- 或直接使用云平台提供的监控服务(如阿里云云监控)。
常见问题解答
Q1:服务器连接超时如何处理?
- 检查安全组/防火墙是否开放SSH端口(默认22)。
- 通过云平台控制台重启实例或重置密码。
Q2:Nginx报错“Permission Denied”如何解决?
- 检查目录权限:
sudo chown -R www-data:www-data /var/www/html
- 确认SELinux状态(仅限CentOS):
sudo setenforce 0
Q3:如何优化服务器响应速度?
- 启用Gzip压缩:在Nginx配置中添加
gzip on;
。 - 使用CDN加速静态资源分发。
参考资料
- Nginx官方文档:https://nginx.org/en/docs/
- Let’s Encrypt证书申请指南:https://letsencrypt.org/getting-started/
- AWS EC2用户手册:https://docs.aws.amazon.com/ec2/
- Linux权限管理最佳实践:https://wiki.archlinux.org/title/Users_and_groups