Linux 云服务器

买一台云主机后要做的安全与基础配置:密钥登录、防火墙、时区、swap。

Beginner
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.10
Bash
# 服务器上 /etc/ssh/sshd_config
PasswordAuthentication no
PermitRootLogin no
Port 2222
Bash
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/fstab
Do not run apps as root, and never expose database ports. Scanners try 3306 and 6379 within minutes of boot.

Friends & Partners