NodeJS – 4. Deploy Github và Heroku, Trỏ Domain qua Cloudflare

Author: - Posted: 04/05/21 - Update: 04/05/21

I. Đẩy từ Local lên Git

- Tại file ./.gitignore

- Tại file ./.env

- Tại file ./Procfile

- Tại file ./src/server.js , cần lưu ý cổng PORT

-- Đầy đủ các mục trên là có thể đẩy tạm thời lên git được rồi

II. Deploy lên Heroku

1. Cấu hình

- Tại file ./src/server.js , cần lưu ý cổng PORT

- Tạo file "Procfile" (không có đuôi mở rộng) tại thư mục gốc: ./Procfile

2. Cách 1: Deploy lên Heroku bằng Heroku Git

- Bước 1: Cài Heroku CLI
- Bước 2: Dùng Command Prompt với quyền Administrator (từ lần thứ 2 trở đi, có thể dùng Terminal của VSCode)

heroku login

cd my-project/
git init
heroku git:clone -a yourproject

git add .
git commit -am "make it better"
git push heroku master

3. Cách 2: Deploy lên Heroku bằng Github

- Trên trang heroku, phần Deploy -> Deployment method: chọn phương thức Github
- Tích chọn: Automatic deploys from master are enabled

- Dùng trình duyệt vào website hưởng thành quả, VD: https://medihome-vn.herokuapp.com/manager

4. Tạo biến thay file .env

-- Vào Setting -> Config Vars -> Thêm biến tương ứng cặp Key - Value

KEY: MONGODB_URI
VALUE: mongodb+srv://root:[email protected]/test?retryWrites=true

III. Trỏ tên miền từ Cloudflare về Heroku

1. Trên Heroku -> Settings -> Add Domain
-> Lấy DNS Target, trông dạng như sau:

polished-spider-g32lzit2sw0tgd521lnn6pwl.herokudns.com

2. Trên Cloudflare

CNAME medihome.vn polished-spider-g32lzit2sw0tgd521lnn6pwl.herokudns.com
CNAME www polished-spider-g32lzit2sw0tgd521lnn6pwl.herokudns.com

-- Nhớ trỏ nameserver từ domain -> về cloudflare. Ví dụ:

Nameserver 1 ben.ns.cloudflare.com
Nameserver 2 may.ns.cloudflare.com

3. Trên Cloudflare -> SSL/TLS
- Chọn Flexible (nghĩa là dùng SSL từ Browser đến Cloudflare, còn từ Cloudflare đến Heroku thì ko có SSL)