系统准备
相关链接
1. 系统更新
sudo apt update
sudo apt upgrade
2. 基础工具安装
常见工具
# Git
sudo apt install git -y
# 网络工具
sudo apt install net-tools -y
# 编辑器
sudo apt install vim -y
# 压缩工具
sudo apt install unzip -y
# SSH服务
sudo apt install openssh-server -y
# 云工具
sudo apt install cloud-guest-utils -y
# Redis
sudo apt install redis -y
# Nginx
sudo apt install nginx -y
# 桌面环境增强
sudo apt install open-vm-tools-desktop open-vm-tools
sudo reboot
其他常见工具,按需求下载
开发相关
| 工具 | 用途 |
|---|---|
build-essential | gcc / g++ / make 等编译工具 |
python3 / python3-pip | Python 开发与脚本 |
nodejs / npm / yarn | Node 前端环境 |
docker / docker-compose | 容器化部署 |
git | 版本控制 |
curl / wget | 网络请求测试、下载 |
网络/调试
| 工具 | 用途 |
|---|---|
net-tools | ifconfig、netstat |
iproute2 | ip addr / ss(比 net-tools 更新) |
traceroute | 路由追踪 |
telnet | 测试端口连通性 |
nmap | 端口扫描/网络排查 |
tcpdump | 网络抓包分析 |
系统管理
| 工具 | 用途 |
|---|---|
htop | 高级进程管理 |
screen / tmux | 终端多路复用 |
tree | 文件夹结构树状显示 |
lsof | 查看打开文件/端口 |
ufw | 防火墙管理(Ubuntu 默认防火墙) |
chrony / ntp | 网络时间同步 |
压缩/归档工具
| 工具 | 用途 |
|---|---|
zip / unzip | 压缩/解压 |
tar / gzip / bzip2 | 常用归档 |
p7zip-full | 7z 格式压缩解压 |
数据库相关
| 工具 | 用途 |
|---|---|
redis | 内存缓存 |
mysql-client / mysql-server | MySQL 数据库 |
postgresql / postgresql-client | PostgreSQL 数据库 |
sqlite3 | 轻量数据库 |
Web / 服务相关
| 工具 | 用途 |
|---|---|
nginx | Web 服务器 |
apache2 | 备选 Web 服务器 |
certbot | HTTPS 证书申请 |
ufw | 防火墙管理 |
openssh-server | SSH 服务 |
系统增强 / 虚拟化
| 工具 | 用途 |
|---|---|
open-vm-tools / open-vm-tools-desktop | 虚拟机增强 |
virt-top / virt-manager | 虚拟化管理 |
ncdu | 磁盘使用分析 |
mlocate | 文件快速查找 |
编辑器 / 文件工具
| 工具 | 用途 |
|---|---|
vim | 编辑器 |
nano | 简单编辑器 |
mc | 控制台文件管理器 |
less / more | 查看日志 |
3. 防火墙配置
# 查看 UFW 状态(默认可能是 inactive)
sudo ufw status verbose
# 启用 UFW
sudo ufw enable
-
UFW 默认拒绝所有入站连接,允许所有出站连接
-
启用前建议先允许 SSH,避免自己被锁在服务器外
# 允许 SSH(默认端口 22)
sudo ufw allow ssh
# 允许 HTTP(端口 80)
sudo ufw allow 80
# 可选:允许 HTTPS(端口 443)如果计划启用 SSL
# sudo ufw allow https
检查规则是否生效:
sudo ufw status
结果示例:
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
80/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
80/tcp (v6) ALLOW Anywhere (v6)
如果你希望普通用户可以执行 UFW 命令无需输入密码,可编辑 sudoers 文件:
# 配置 sudo 权限(可选)
sudo visudo
# 在文件末尾添加:
# username ALL=(ALL) NOPASSWD: /usr/sbin/ufw
-
username替换成你实际用户名 -
只对
/usr/sbin/ufw命令免密码,其他 sudo 命令仍需密码 -
提高自动化脚本执行效率,但略降低安全性
SSH 端口可修改,避免暴力攻击:
sudo ufw allow 2222/tcp
默认拒绝其他入站连接(UFW 默认即拒绝,可显式设置):
sudo ufw default deny incoming
sudo ufw default allow outgoing
重载防火墙规则:
sudo ufw reload
4. MySQL 安装与配置
# 安装 MySQL
sudo apt install mysql-server mysql-client -y
# 检查状态
sudo systemctl status mysql
mysql --version
# 设置开机自启
sudo systemctl enable mysql
sudo systemctl start mysql
# 安全配置
sudo mysql_secure_installation
# 配置 root 密码
sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpassword';
FLUSH PRIVILEGES;
EXIT;
# 重启 MySQL
sudo systemctl restart mysql
# 创建软链接(如果需要)
sudo ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock
5. 磁盘扩展(如果需要)
# 查看磁盘信息
sudo fdisk -l
df -h
lsblk
# 扩展分区
sudo growpart /dev/sda 2
sudo resize2fs /dev/sda2
df -h
6. Node.js 环境配置
# 安装 Node.js 和 npm
sudo apt install nodejs npm -y
# 检查版本
node -v
npm -v
# 安装 Vue CLI
sudo npm install -g @vue/cli
vue --version
7. Conda 环境配置
# 下载并安装 Anaconda
sudo wget https://repo.anaconda.com/archive/Anaconda3-2024.06-1-Linux-x86_64.sh
bash ./Anaconda3-2024.06-1-Linux-x86_64.sh -b
sudo rm Anaconda3-2024.06-1-Linux-x86_64.sh
# 配置环境变量
sudo vim ~/.bashrc
source ~/.bashrc
export PATH=~/anaconda3/bin:$PATH
source ~/.bashrc
# 检查安装
conda --version
# 创建 Python 环境
conda create --name django_env python=3.10
conda init
source ~/.bashrc
conda activate django_env
# 或者
sudo apt install python3 python3-pip python3-venv
python3 -m venv .venv
source .venv/bin/activate
# 或者
sudo apt install python3-virtualenv
pip install virtualenv
virtualenv venv
source venv/bin/activate
项目部署
1. 获取代码
cd /var/www
git clone 你的仓库
sudo chmod 777 -R 你的目录
2. 后端部署
2.1 环境配置
cd 项目/django项目/
pip install -r requirements.txt
2.2 配置文件
创建并编辑 .env 文件:
sudo vim .env
配置内容:
# MySQL 配置
DB_NAME=数据库
DB_USER=root
DB_PASSWORD=你的密码
DB_HOST=127.0.0.1
DB_PORT=3306
# Django 配置
SECRET_KEY=your_secret_key
LANGUAGE_CODE=zh-hans
TIME_ZONE=Asia/Tokyo
# 静态文件配置
STATIC_URL=/static/
STATIC_ROOT=staticfiles
MEDIA_URL=/media/
MEDIA_ROOT=media
2.3 启动服务
# 进入 Django 项目根目录(manage.py 所在目录)
# 启动开发服务器,绑定本机所有 IP,方便外部访问
python manage.py runserver 0.0.0.0:8000
-
0.0.0.0:8000可以让同网段的其他机器访问 -
默认
127.0.0.1:8000只能本机访问 -
开发服务器 不适合生产环境,性能低、安全性差
在浏览器或命令行 curl:
curl http://192.168.10.39:8000/
-
如果能返回 Django 默认页面或 API 数据,说明服务正常
-
如果报错,需要检查:
python环境INSTALLED_APPS- 数据库连接
- 端口是否被占用
Django 的 内置开发服务器只是测试用,生产环境需要:
- 高并发处理能力
- 多进程 / 多线程
- 能与 Nginx 配合反向代理
Gunicorn 是常用的 WSGI 服务器,配合 Nginx
[浏览器/客户端]
│
▼
[Nginx] ← 静态资源(Vue 打包后的 JS/CSS/图片等)
│
├── /static 或 /media 直接返回静态文件
│
└── /prod-api/ 反向代理请求到 → [Gunicorn] → [Django App]
- Vue 前端
- 打包成静态文件(
dist/) - Nginx 直接提供这些静态文件,性能高
- Vue 不会直接访问 Gunicorn
- Nginx
- 负责静态文件服务(HTML/JS/CSS/图片/字体)
- 负责反向代理 API 请求(比如
/prod-api/)到 Gunicorn - 可以做 gzip、缓存、SSL、限流等优化
- Gunicorn
- WSGI 服务器,运行 Django
- 接收 Nginx 代理的请求,处理业务逻辑、数据库操作
- 不能直接处理静态文件(性能低)
- 支持 systemd 管理,实现开机自启
- 稳定、高性能、可管理多个 worker
- 能够在 80/443 端口提供服务(通过 Nginx 反向代理)
- Django App
- 处理 API / 后端逻辑
- 管理数据库、缓存、权限等
- 通过 Gunicorn 提供 WSGI 接口
3. 前端部署
3.1 构建
cd your-vue-project
npm install
npm run build:prod
4. Nginx 配置
4.1 创建站点配置文件
创建站点配置文件:
sudo nano /etc/nginx/sites-available/192.168.10.39.conf
并写入以下配置:
# /etc/nginx/sites-available/192.168.10.39.conf
server {
listen 80;
listen [::]:80;
server_name 你的ip/域名;
charset utf-8;
root /var/www/前端构建产物目录/dist;
index index.html;
# 安全相关
include nginxconfig.io/security.conf;
# 日志配置
access_log /var/log/nginx/access.log combined buffer=512k flush=1m;
error_log /var/log/nginx/error.log warn;
# Vue SPA 路由回退
location / {
try_files $uri /index.html;
}
# Django API 反向代理
location /prod-api/ {
proxy_pass http://127.0.0.1:8000/;
proxy_set_header Host $host;
include nginxconfig.io/proxy.conf;
}
# Django 静态文件
location /django-static/ {
alias /var/www/backstage-admin/fs_admin/staticfiles/;
expires 1y;
add_header Cache-Control "public";
try_files $uri =404;
}
# Django 媒体文件
location /media/ {
alias /var/www/backstage-admin/fs_admin/media/;
expires 1y;
add_header Cache-Control "public";
try_files $uri =404;
}
# 通用配置(gzip / favicon / assets)
include nginxconfig.io/general.conf;
}
-
root只在server级别声明,避免 location 行为不一致 -
try_files $uri $uri/ /index.html是 SPA 必备 -
Django 使用
alias,避免路径拼接错误
4.2 启用站点,创建符号链接
/etc/nginx/
├── sites-available/ # 所有站点配置(草稿区 / 仓库)
│ └── 192.168.10.39.conf
│
├── sites-enabled/ # 当前生效的站点(开关区)
│ └── 192.168.10.39.conf -> ../sites-available/192.168.10.39.conf
# 创建符号链接以启用站点
sudo ln -s /etc/nginx/sites-available/192.168.10.39.conf /etc/nginx/sites-enabled/
# 验证
ls -l /etc/nginx/sites-enabled/
-
sites-available:配置存放区(不会自动生效) -
sites-enabled:实际被 Nginx 加载的配置 -
删除软链接即可下线站点(无需删配置)
4.3 创建公共配置目录(模块化配置)
sudo mkdir -p /etc/nginx/nginxconfig.io
-
存放可复用的配置片段
-
通过
include引入 -
避免每个 server 重复配置
4.4 通用配置:general.conf
# /etc/nginx/nginxconfig.io/general.conf
# favicon.ico
location = /favicon.ico {
log_not_found off;
}
# robots.txt
location = /robots.txt {
log_not_found off;
}
# assets, media
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
expires 7d;
}
# svg, fonts
location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
add_header Access-Control-Allow-Origin "*";
expires 7d;
}
# gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
application/json
application/javascript
text/javascript
application/x-javascript
application/xml
application/xml+rss
image/svg+xml;
log_not_found off;: 如果请求丢失,不记录日志expires 7d: 7 天缓存dd_header Access-Control-Allow-Origin "*";:允许跨域
4.5 反向代理配置:proxy.conf
# /etc/nginx/nginxconfig.io/proxy.conf
proxy_http_version 1.1;
# Proxy SSL
proxy_ssl_server_name on;
# Proxy headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
# Proxy timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
-
Upgrade:支持 WebSocket 升级 -
Connection:支持 WebSocket 连接 -
X-Real-IP:客户端真实 IP -
X-Forwarded-For:代理链客户端 IP -
X-Forwarded-Proto:原始请求协议(http / https) -
X-Forwarded-Host:原始请求 Host -
X-Forwarded-Port:原始请求端口 -
proxy_connect_timeout:与后端建立连接超时 -
proxy_send_timeout:发送请求到后端超时 -
proxy_read_timeout:等待后端响应超时 -
保留真实客户端 IP
4.6 安全配置:security.conf
# /etc/nginx/nginxconfig.io/security.conf
# security headers
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
add_header Permissions-Policy "interest-cohort=()" always;
# . files
location ~ /\.(?!well-known) {
deny all;
}
X-XSS-Protection:检测到 XSS 攻击时直接阻止渲染页面X-Content-Type-Options:防止浏览器 MIME 类型嗅探,只按照服务器声明的 Content-Type 解析资源Referrer-Policy:表示从 HTTPS 到 HTTP 时不发送 RefererContent-Security-Policy:防止浏览器 MIME 类型嗅探X-Content-Type-Options:内容安全策略- 限制资源加载源,防止 XSS 和数据注入
'self'仅允许同源http: https: ws: wss: data: blob: 'unsafe-inline'等允许特定资源类型frame-ancestors 'self'防止页面被嵌入 iframe
Permissions-Polic:禁用 FLoC(谷歌广告追踪)- 拒绝访问除了 .well-known 目录外的所有隐藏文件
4.7 配置生效
sudo nginx -t
sudo systemctl reload nginx
5. Gunicorn 配置
5.1 安装 Gunicorn
# 激活 Django 项目虚拟环境
source /path/to/虚拟环境/bin/activate
# 安装 Gunicorn
pip install gunicorn
安装完成后可以用 gunicorn --version 验证
5.2 创建 systemd 服务文件
sudo vim /etc/systemd/system/gunicorn.service
配置内容:
[Unit]
Description=gunicorn daemon for Django
After=network.target
[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/后端目录/django项目
ExecStart=/path/to/虚拟环境/bin/gunicorn\
--access-logfile - \
--workers 3 \
--bind 127.0.0.1:8000 \
django项目.wsgi:application
Environment="DJANGO_SETTINGS_MODULE=django项目.settings"
Environment="PYTHONUNBUFFERED=1"
Restart=always
[Install]
WantedBy=multi-user.target
Group:所属用户组,通常与 Nginx 相同access-logfile:访问日志输出到 stdoutworkers 3:工作进程数量,建议 CPU 核数 * 2 + 1bind 127.0.0.1:8000:绑定本机端口,Nginx 通过反向代理访问django项目.wsgi:application:Django WSGI 应用入口Environmen:Django 配置文件PYTHONUNBUFFERED=1:禁用 Python 输出缓冲Restart=always:出现故障自动重启WantedBy=multi-user.target:开机自启
5.3 启动和管理服务
# 避免中文路径出问题
sudo systemctl daemon-reexec
# 重新加载 systemd 配置
sudo systemctl daemon-reload
# 启动 Gunicorn
sudo systemctl start gunicorn
# 设置开机自启
sudo systemctl enable gunicorn
# 查看服务状态
sudo systemctl status gunicorn
常用命令:
# 重启服务
sudo systemctl restart gunicorn
# 查看日志(实时输出)
journalctl -u gunicorn -f
# 基本命令行启动
gunicorn django项目.wsgi:application --bind 127.0.0.1:8000 --workers 3 --access-logfile -
# 后台运行
gunicorn django项目.wsgi:application --bind 127.0.0.1:8000 --workers 3 &
注意事项
- 请确保替换所有配置文件中的占位符(如密码、路径等)
- 确保所有必要的端口都已开放
- 检查文件权限是否正确
- 定期备份数据库
- 监控系统日志以排查问题
系统日志查看
1. Nginx 日志
# 访问日志
sudo tail -f /var/log/nginx/access.log
# 错误日志
sudo tail -f /var/log/nginx/error.log
# 查看最后100行
sudo tail -n 100 /var/log/nginx/error.log
2. Gunicorn 日志
# 查看 Gunicorn 服务状态和日志
sudo systemctl status gunicorn
# 查看详细日志
sudo journalctl -u gunicorn
# 实时查看日志
sudo journalctl -u gunicorn -f
# 查看最近的日志
sudo journalctl -u gunicorn --since "1 hour ago"
3. MySQL 日志
# 错误日志
sudo tail -f /var/log/mysql/error.log
# 慢查询日志
sudo tail -f /var/log/mysql/mysql-slow.log
4. 系统日志
# 系统日志
sudo tail -f /var/log/syslog
# 内核日志
sudo dmesg | tail
# 查看系统服务状态
sudo systemctl status
5. 日志分析技巧
- 使用 grep 过滤关键字:
# 在 Nginx 错误日志中查找 404 错误
sudo grep "404" /var/log/nginx/error.log
# 在系统日志中查找特定服务
sudo grep "gunicorn" /var/log/syslog
- 使用 less 查看大文件:
# 使用 less 查看日志文件
sudo less /var/log/nginx/error.log
# 在 less 中搜索(按 / 后输入关键字)
# 按 n 查找下一个
# 按 N 查找上一个
# 按 q 退出
- 日志轮转:
# 查看日志轮转配置
sudo cat /etc/logrotate.d/nginx
sudo cat /etc/logrotate.d/mysql
# 手动执行日志轮转
sudo logrotate -f /etc/logrotate.d/nginx
- 常见问题排查:
# 检查磁盘空间
df -h
# 检查内存使用
free -h
# 检查系统负载
top
htop # 如果已安装
- 日志清理:
# 清理旧的日志文件
sudo find /var/log -type f -name "*.gz" -delete
sudo find /var/log -type f -name "*.old" -delete
# 清空日志文件(谨慎使用)
sudo truncate -s 0 /var/log/nginx/error.log
6. 日志监控建议
- 定期检查日志文件大小
- 设置日志轮转策略
- 配置日志告警(如使用 fail2ban)
- 保留重要日志的备份
- 使用日志分析工具(如 ELK Stack)