Mục tiêu: bạn sẽ có một instance EC2 “sạch”, chạy Ubuntu 22.04 LTS, cài Docker + Docker Compose, tự động kéo mã nguồn từ GitHub và khởi chạy ứng dụng NestJS trong container. Hướng dẫn cũng kèm các mẹo mở rộng ổ đĩa, tối ưu bảo mật và vận hành lâu dài.
0. Chuẩn bị
Thành phần | Ghi chú |
---|---|
AWS account | Quyền tạo EC2, EBS, Security Group |
SSH key pair | Đã tải .pem về máy local |
Repo GitHub | Chứa mã nguồn NestJS, Dockerfile , docker-compose.yml , file .env.* … |
Tên miền (tùy chọn) | Nếu muốn cấu hình HTTPS bằng Nginx + Let’s Encrypt |
1. Khởi tạo & cấu hình EC2
- Tạo instance
- AMI: Ubuntu 22.04 LTS (Amazon Linux 2 cũng được, câu lệnh tương tự).
- Kiểu máy: t2.micro / t3a.micro / c5.large… tùy lưu lượng.
- EBS: ≥ 20 GB (có thể tăng sau).
- Security Group Cổng Mục đích 22 SSH 3000 NestJS (nếu chưa dùng reverse proxy) 80 HTTP (Nginx) 443 HTTPS (Nginx)
- SSH vào máy
ssh -i "my_key_ec2_1.pem" ubuntu@<EC2_PUBLIC_IP>
2. Cập nhật hệ điều hành & cài Docker
# Cập nhật OS
sudo apt update && sudo apt upgrade -y
# Cài Docker
curl -fsSL https://get.docker.com | sudo bash
# Tạo group docker để chạy không cần sudo (tùy ý)
sudo usermod -aG docker ubuntu
newgrp docker # nạp lại group
# Cài Docker Compose plugin (phiên bản mới)
sudo apt install -y docker-compose-plugin
# Kiểm tra
docker --version
docker compose version
Tip: nếu vẫn muốn dùng
docker-compose
v1, cài góidocker-compose
. Tuy nhiên câu lệnh mới làdocker compose
(không gạch).
3. Tạo SSH key & thêm vào GitHub (Deploy Key)
ssh-keygen -t ed25519 -C "ec2-github-deploy" -f ~/.ssh/ec2-github-deploy
cat ~/.ssh/ec2-github-deploy.pub
- Vào GitHub Repo → Settings → Deploy keys → Add deploy key
- Dán public key và tích “Allow write access” nếu cần push (thường không).
Cấu hình ~/.ssh/config
cat <<'EOF' > ~/.ssh/config
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/ec2-github-deploy
IdentitiesOnly yes
StrictHostKeyChecking no
EOF
chmod 600 ~/.ssh/config
Kiểm tra:
ssh -T git@github.com # mong đợi thông báo authenticated
4. Clone mã nguồn & chuẩn bị biến môi trường
git clone git@github.com:Username/my-reponsitory-be.git
cd my-reponsitory
- Đặt .env
- Cách nhanh: SCP từ máy local ⇒ EC2:
scp -i "my_key_ec2_1.pem" .env.production ubuntu@<EC2_PUBLIC_IP>:~/my-reponsitory-be/.env
- Hoặc tạo trực tiếp, nhớ KHÔNG commit file bí mật.
- Cách nhanh: SCP từ máy local ⇒ EC2:
5. Build & chạy bằng Docker Compose
docker compose --env-file .env up -d --build
docker ps # kiểm tra container
Khi cần rebuild sạch
docker compose down --volumes docker system prune -af --volumes docker compose --env-file .env up -d --build
6. Reverse proxy & HTTPS (khuyên dùng)
- Cài Nginx
sudo apt install -y nginx sudo ufw allow 'Nginx Full'
- Virtual Host
server { listen 80; server_name api.example.com; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; 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; } }
sudo ln -s /etc/nginx/sites-available/nest /etc/nginx/sites-enabled/ sudo nginx -t && sudo systemctl reload nginx
- HTTPS với Let’s Encrypt (Certbot)
sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d api.example.com
Tự động gia hạn:systemctl status certbot.timer
7. Tự động khởi động (systemd)
Tạo file /etc/systemd/system/example.service
:
[Unit]
Description=Docker Compose NestJS
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
WorkingDirectory=/home/ubuntu/my-reponsitory-be
ExecStart=/usr/bin/docker compose --env-file .env up -d
ExecStop=/usr/bin/docker compose down
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
sudo systemctl enable example # Kích hoạt chạy cùng hệ thống
sudo systemctl start example # Bắt đầu chạy ngay lập tức
8. Giám sát & log
Việc | Lệnh |
---|---|
Xem log container | docker compose logs -f --tail 50 |
Dọn rác Docker | docker system prune -af --volumes |
Kiểm tra dung lượng | df -h |
9. Mở rộng dung lượng EBS & filesystem
- Tăng EBS trong AWS Console.
- SSH vào máy, cài công cụ:
sudo apt install -y cloud-guest-utils
- Mở rộng phân vùng & filesystem (Ubuntu, ext4):
sudo growpart /dev/xvda 1 sudo resize2fs /dev/xvda1
- Kiểm tra:
df -h
(đã nhận đủ dung lượng).
10. Kết nối tới PostgreSQL RDS (tham khảo)
psql -h your-database-host.rds.amazonaws.com \
-p 5432 -U your-username -d your-database-name
11. Các mẹo & bước bổ sung
Hạng mục | Ghi chú |
---|---|
Swap file | Tạo swap 1–2 GB cho t2.micro: sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile |
Dockerfile tối ưu | Dùng multi‑stage build (node:20-alpine ), thêm .dockerignore để giảm kích thước ảnh. |
CI/CD | Dùng GitHub Actions: build & push image → SSH trigger docker compose pull && docker compose up -d . |
Backup | Snapshot EBS + backup RDS. |
Monitoring | Cài CloudWatch Agent hoặc prom/node-exporter → Grafana. |
Bảo mật | Bật MFA AWS, hạn chế IP SSH, bật AWS GuardDuty. |
12. Kiểm tra sức khỏe ứng dụng
# Qua Nginx
curl https://api.example.com/health
# Hoặc direct port
curl http://<EC2_PUBLIC_IP>:3000/health