Linux 云服务器
买一台云主机后要做的安全与基础配置:密钥登录、防火墙、时区、swap。
Key Points云主机开箱就有公网 IP,第一件事是关掉密码登录、改 SSH 端口、配安全组,而不是先装环境。
第一次登录
Bash
ssh root@203.0.113.10
# 或指定密钥
ssh -i ~/.ssh/id_ed25519 ubuntu@203.0.113.10密钥登录
Bash
# 本地生成密钥(已有就跳过)
ssh-keygen -t ed25519 -C "me@example.com"
# 推到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub ubuntu@203.0.113.10Bash
# 服务器上 /etc/ssh/sshd_config
PasswordAuthentication no
PermitRootLogin no
Port 2222Bash
sudo systemctl restart ssh
# 改端口后记得放行安全组与新端口,否则会被锁在外面安全组与防火墙
The cloud security group filters outside the VM; ufw/firewalld filters inside. Open the port in both layers, and only what you need: 22 (or a custom SSH port), 80, 443.
Bash
sudo ufw allow 2222/tcp
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose基础配置
Bash
sudo timedatectl set-timezone Asia/Shanghai
sudo hostnamectl set-hostname api-01
# 小内存机器加 swap(1GB 内存的机器尤其需要)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabDo not run apps as root, and never expose database ports. Scanners try 3306 and 6379 within minutes of boot.
第一次登录
Bash
ssh root@203.0.113.10
# 或指定密钥
ssh -i ~/.ssh/id_ed25519 ubuntu@203.0.113.10密钥登录
Bash
# 本地生成密钥(已有就跳过)
ssh-keygen -t ed25519 -C "me@example.com"
# 推到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub ubuntu@203.0.113.10Bash
# 服务器上 /etc/ssh/sshd_config
PasswordAuthentication no
PermitRootLogin no
Port 2222Bash
sudo systemctl restart ssh
# 改端口后记得放行安全组与新端口,否则会被锁在外面安全组与防火墙
云厂商的安全组在机器外面做过滤,ufw/firewalld 在机器里面。两层都要开对应端口,只开必要的:22(或自定义 SSH)、80、443。
Bash
sudo ufw allow 2222/tcp
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose基础配置
Bash
sudo timedatectl set-timezone Asia/Shanghai
sudo hostnamectl set-hostname api-01
# 小内存机器加 swap(1GB 内存的机器尤其需要)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab别用 root 跑应用,也别把数据库端口开到公网。云上的扫描器在你开机后几分钟内就会来试 3306 和 6379。