--- tags: Blue 的學習紀錄, Node.js --- # Node.js - NGINX, SSL With Lets Encrypt ## 目標 跟著下面影片的教學,簡單快速的架設 Nginx 並且安裝 SSL 在 Node server 上 <iframe width="560" height="315" src="https://www.youtube.com/embed/oykl1Ih9pMg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> ## 情境 已購買一個網域 並且擁有一台遠端主機(例如 Linode or DigitalOcean) ## 流程 <https://gist.github.com/bradtraversy/cd90d1ed3c462fe3bddd11bf8953a896> ### 安裝 process manage 使用 pm2 這個套件,讓 Node server 跑在背景服務 npm 頁面: <https://www.npmjs.com/package/pm2> 官方文件: <https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/> #### 安裝 pm2 ```bash= sudo npm i pm2 -g ``` #### 用 pm2 使 Node 執行在背景 ```bash= pm2 start app.js --name "process name" --watch --ignore-watch="node_modules" ``` `--name`:process 的名稱 `--watch`:當前目錄及所有子目錄中,若任何檔案更動時,自動重啟 process `--ignore-watch`:忽略特定檔案不要 watch #### 查看狀態 ```bash= pm2 status pm2 logs ``` #### 設定為 startup 當主機重啟開機時,使 Node server 也自動重啟 ```bash= pm2 startup pm2 save ``` #### 重啟主機以確定一切如預期運作 ```bash= # 重啟主機 reboot ... # 重啟完後查看 Node server 是否有在背景執行 pm2 status ``` :::info 至此,已經可以輸入 `domain name:port` 進入 Node server ::: ### 安裝簡易防火牆 使用 `ufw` 這款套件,來幫助我們對於 port 的管理 #### 安裝 ufw ```bash= # 安裝 ufw apt-get install ufw # 啟用 ufw ufw enable ``` #### 設定要開啟的 port 開啟 ssh、http、https 的 port ```bash= ufw allow ssh ufw allow http ufw allow https ``` #### 查看 ufw 的狀態 ```bash= ufw status ``` :::info 因為設定了防火牆,所以原來 Node server 所 listen 的 port 就無法存取了 ::: ### 安裝 Nginx ```bash= sudo apt install nginx ``` 安裝好後,在瀏覽器以 ==http== 的方式連線到 domain name,會顯示 Nginx 成功安裝的畫面 ### 設定 Nginx 讓 Nginx 知道該如何導向 request 到 `/etc/nginx/sites-available/default` 中 於 Server 底下新增: ```bash= proxy_pass http://localhost:8080; #whatever port your app runs on proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; ``` 關於各項設定背後的涵義,我還沒有研究,有機會的話再補充 ```bash= # Check NGINX config sudo nginx -t # Restart NGINX sudo service nginx restart ``` 到這邊為止,已經做完了 Nginx 方面的設定 ### LetsEncrypt 安裝 LetsEncrypt 超級簡單,短短幾行就結束,其背後的運作機制以後有機會再來研究補充 ```bash= sudo apt-get install python-certbot-nginx sudo certbot --nginx -d yourdomain.com # Only valid for 90 days, test the renewal process with certbot renew --dry-run ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.