简介:本文详细讲解如何将本地网站部署到云服务器,涵盖云服务器选择、环境配置、代码上传、域名绑定等全流程,适合开发者和企业用户参考。
选择云服务器时需考虑以下核心因素:
.com或.cn后缀,年费约50-100元。使用SSH工具(如Xshell、Terminus)连接服务器:
ssh username@服务器IP -p 端口号# 示例:ssh root@123.123.123.123 -p 22
首次连接需确认指纹,输入密码后完成登录。
Nginx安装(Ubuntu示例):
sudo apt updatesudo apt install nginx -ysudo systemctl start nginxsudo systemctl enable nginx
访问服务器IP应看到Nginx欢迎页。
Apache安装(可选):
sudo apt install apache2 -ysudo systemctl start apache2
sudo apt install mysql-server -ysudo mysql_secure_installation # 设置root密码
sudo apt install mongodb -ysudo systemctl start mongodb
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -sudo apt install -y nodejs
sudo apt install python3 python3-pip -y
在服务器创建项目目录并克隆代码:
mkdir -p /var/www/mywebsitecd /var/www/mywebsitegit clone https://github.com/yourname/yourrepo.git .
本地执行:
scp -r /本地路径/项目 root@服务器IP:/var/www/mywebsite
cd /var/www/mywebsitenpm installnpm run build # 生成静态文件
pip install -r requirements.txtpython manage.py collectstatic
编辑/etc/nginx/sites-available/mywebsite:
server {listen 80;server_name yourdomain.com;root /var/www/mywebsite/dist; # 静态文件目录index index.html;location / {try_files $uri $uri/ /index.html;}# 代理API请求(如Node.js后端)location /api/ {proxy_pass http://localhost:3000;proxy_set_header Host $host;}}
启用配置:
sudo ln -s /etc/nginx/sites-available/mywebsite /etc/nginx/sites-enabled/sudo nginx -t # 测试配置sudo systemctl restart nginx
编辑/etc/apache2/sites-available/mywebsite.conf:
<VirtualHost *:80>ServerName yourdomain.comDocumentRoot /var/www/mywebsiteErrorLog ${APACHE_LOG_DIR}/error.logCustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>
启用配置:
sudo a2ensite mywebsite.confsudo systemctl restart apache2
使用Let’s Encrypt免费证书:
sudo apt install certbot python3-certbot-nginx -ysudo certbot --nginx -d yourdomain.com
证书自动续期配置:
sudo certbot renew --dry-run # 测试续期
sudo ufw allow 22/tcp # SSHsudo ufw allow 80/tcp # HTTPsudo ufw allow 443/tcp # HTTPSsudo ufw enable
在云服务商控制台配置安全组规则:
http://yourdomain.com验证页面加载。/api/users)是否正常返回数据。/var/log/nginx/access.logjournalctl -u nginx -fhtop查看CPU/内存占用。systemctl status nodejstail -f /var/log/nginx/error.lognetstat -tulnp查看端口占用。
sudo chown -R www-data:www-data /var/www/mywebsitesudo chmod -R 755 /var/www/mywebsite
配置阿里云CDN或Cloudflare,将静态资源缓存至边缘节点。
使用GitHub Actions或Jenkins实现代码推送后自动构建部署:
# GitHub Actions示例name: Deployon: [push]jobs:deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- run: scp -r * user@server:/var/www/mywebsite
多服务器场景下配置Nginx负载均衡:
upstream backend {server 192.168.1.1:3000;server 192.168.1.2:3000;}server {location / {proxy_pass http://backend;}}
通过本文的步骤,您已掌握从云服务器选型到网站部署的全流程。关键点包括:
建议初学者先在测试环境练习,熟悉后再部署生产环境。遇到问题时,可查阅云服务商文档或社区论坛(如Stack Overflow)。