整自己blog #8 Docker + Route 53 + nginx

導覽

正文

Set up 完個server 當然係放返自己寫既野上去
首先dockerize 左隻strapi
事前準備要記得裝埋docker
唔係會run 唔到 dockerize.png

npx @strapi-community/dockerize@latest

run 完就會prompt 叫大家填返database type 密碼之類
咁就照填postgres 5432 啦

npx @strapi-community/dockerize new
--projectname=<projectname>
--dbtype=<dbclient>
--dbhost=<dbhost>
--dbport=<dbport>
--dbname=<dbname>
--dbusername=<dbusername>
--dbpassword=<dbpassword>
--projecttype=<projecttype>
--packagemanager=<packagemanager>
--usecompose=<usecompose>
--env=<env>

做完之後可以試下

docker compose up

成功既話上localhost:1337 會見到同之前npm run build 一樣既畫面
咁就證明個docker image ready 啦
下一步當然係upload 上server
呢度會有幾個選擇
用docker hub / aws ecr (aws 既docker hub) / putty push上去server
我就貪得意用左aws ecr
因為free tier 既docker hub 只可以private 一隻docker image

首先authenticate左先

aws ecr get-login-password --region region | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.region.amazonaws.com

之後俾個名個image就可以pull image

docker tag LOCAL_DOCKER_IMAGE_NAME aws_account_id.dkr.ecr.us-west-2.amazonaws.com/my-repository:tag
docker push aws_account_id.dkr.ecr.us-west-2.amazonaws.com/my-repository:tag

跟住返返server 果邊pull image

docker pull aws_account_id.dkr.ecr.us-west-2.amazonaws.com/amazonlinux:latest

pull完就可以直接run

sudo docker run -d -p 1337:1337 --env-file xxx.txt DOCKER_IMAGE_NAME

呢度我create左一個新既xxx.txt 拎黎裝住.env file 入面既variables
咁樣方便我隨時可以用唔同既env file 係host 唔同既strapi 完成左之後就可以去返ec2 俾既public address 加返個port 1337 睇下
成功左應該會見到以下呢個畫面
strapi cloud.png

眼利既朋友呢刻會發現左上有個insecured
insecure.png 原因係台server 冇ssl certificate
而係ec2 解決呢個問題首先要有一個domain name
咁呢刻就要用route 53 去解決啦
router 53 就係aws 自己既domain host
入到去輸入自己想要既domain name 佢就會一一列出價錢
domain.png

拎左個domain name之後就要將個domain name同ec2 個ip link起黎
入hosted zone 之後create record
arecord.png type 係A record, IP打返ec2 個ip
之後確認,如無意外半個鐘內就會生效

課完金返一返去server 先
呢度要裝nginx 用一用佢既reverse proxying 功能
好多時我地上網會見到domain name 前會有個subdomain name
例如tnlo.me前可能會有個blog blog.tnlo.me 就可以去到某d網頁咁樣之類
但係如果review 返呢篇文章所用既方法
只可以透過specify 個port 去access 個strapi
而reverse proxying就係將呢個1337變成sub domain name既工具啦
install nginx

sudo amazon-linux-extras install nginx1 -y

start nginx

sudo systemctl start nginx
sudo systemctl enable nginx

setup完去一去/etc/conf.d 呢個folder
create 新既config

sudo YOUR_SUBDOMAIN.tnlo.me.conf

nginx.png location 改返SUBDOMAIN 同埋domain name做頭先route 53 register果個
下面既managed by certbot 暫時唔駛理
咁樣set左之後nginx 就會自動route port 1337 既野去左subdomain度啦

set完之後就搞certbot
certbot 係自動renew SSL cert
咁就可以令到server 係行https 同埋insecure 既message 消失
裝certbot

wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto

裝完之後run 以下command
係拎黎prove 呢個domain name 係屬於你

./certbot-auto certonly --standalone -d xyz.yourdomain.com

然後一步一步跟住做
set完後個程式就會自動apply返cert 落nginx度
之後上YOUR_SUBDOMAIN.tnlo.me 就可以見到一個係行ssl 既strapi啦

去到呢度搞完strapi
下一篇就會放nextjs個app上網啦

Copyright © tnlo.me. All rights reserved.