VPC/Route 53 config & Nginx + EC2 最簡單的 EC2 實作🫠
最近因為公司開了幾堂 AWS 的教育訓練,課程結束後老闆們有指派回家作業需要完成,因此把實作的歷程紀錄在這邊(不知道我 k8s 那兩篇啥時才能發佈🫠)
Homework
基本要求
- VPC 建出來要有 Subnet / Route Table
- Route 53 要設定出 sub-domain 要有幾筆 CNAME / A
其實這次的作業蠻簡單的,因為 VPC 預設就會幫我們開好 Subnet 與 route table,麻煩的點是在要理解 Route 53 的服務到底可以幫我們完成什麼事。
HW - record
- Create VPC
- Route table 新增路由連到外網:
- Main route table → Routes → Edit Routes
- Destination: 0.0.0.0/0 , Target: igw-XXXX
- Route table 新增路由連到外網:
- Create EC2
- Setup Route53
- Amplify: 以視覺方式建置 Web 前端 UI
- Deploy your Jekyll Site using AWS Amplify — with only a few clicks
- Amplify console - Domain management: 可以直接在原有的 domain 加上一個 subdomain
問題
- CNAME 應用場景:內部開發方便(設在 private zone)、安全性(設定檔都設 CNAME 的 dns)
- Name server 用處:讓其他人得以 query 到我們自己設定的 dns record
Nginx in EC2
Prerequisite: EC2 w/ SG allowing http & https
Nginx Config
在設定完上述 Route 53 的 A / CNAME record 之後,覺得如果沒有真的開一個 server 顯示一點東西真的太對不起自己ㄌ吧(蛤),於是就放了一個簡單的頁面進去剛剛開好的 EC2 裡
-
下載 nginx & epel
sudo yum install -y epel-release sudo yum install nginx -y
-
Nginx 相關指令
sudo systemctl start nginx sudo systemctl enable nginx sudo systemctl status nginx
-
建立資料夾放置要 serve 的靜態檔案,把 index.html 加到裡面
sudo mkdir /var/www/jc713.staff.5xruby.dev/public_html
-
改變該資料夾的所有權,讓 Nginx 可以存取執行
sudo chown -R nginx: /var/www/jc713.staff.5xruby.dev/
-
Enable SELinux:
sudo vim /etc/selinux/config
將 disable 改成 enable& check
sudo sestatus
-
開放 SELinux 存取 Nginx website files
sudo setsebool -P httpd_can_network_connect on sudo chcon -Rt httpd_sys_content_t /var/www/
-
Nginx 設定檔
sudo vi /etc/nginx/sites-available/jc713.staff.5xruby.dev.conf
server { listen 80; listen [::]:80; root /var/www/example-one.com/public_html; index index.html; server_name example-one.com www.example-one.com; access_log /var/log/nginx/example-one.com.access.log; error_log /var/log/nginx/example-one.com.error.log; location / { try_files $uri $uri/ =404; } }
-
驗證 Nginx 設定
$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
-
Restart Nginx with
sudo systemctl restart nginx
Nginx SSL settings
-
安裝 Certbot
sudo apt install certbot -y sudo apt-get install -y python-certbot-nginx
-
生成 SSL 憑證 & Nginx 設定
$ sudo certbot --nginx ------- 1. You site admin email address 2. Terms of Service agreement. 3. List of domains you need HTTPS for. Certbot will automatically detect this information from the Nginx conf files. 4. HTTP to HTTPS redirection confirmation (it is better to redirect)
-
Certbot 會自動在剛剛設定的 Nginx 設定檔裡產生以下資訊
listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/kartsavings.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/kartsavings.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }
-
Done!