今天準備來將Day04、Day06的東西佈署上來。
先寫個namespace的yaml之後,東西會放在這個namespace底下
這些所有的yaml都是執行 kubectl apply -f xxxx.yml
ithomelab-ns.yml
apiVersion: v1
kind: Namespace
metadata:
name: ithomelab
這邊的話因為資料庫連線字串的考量,程式的部分是設計在Production讀取環境變數取得connection string(開發時讀appsettings.json),而這邊則是使用configMap將connection string儲存起來,供之後deployment的環境變數讀取。
### 程式碼片段
if(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")=="Production")
services.AddDbContext<BloggerContext>(options => options.UseNpgsql(Environment.GetEnvironmentVariable("ConnectionStrings")));
else
services.AddDbContext<BloggerContext>(options => options.UseNpgsql("name=ConnectionStrings:DefaultConnection"));
再多一點安全考量的話,則可以將這段connection string加密後再放入configMap,不過程式端也要實作對應的解密就對了。
kubectl create cm apicm --from-file=api-day04-cm -n ithomelab
Day04 API的deployment,api-day04-deploy.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ithomelab-api-deployment
namespace: ithomelab
labels:
app: ithomelab-api
spec:
replicas: 1
selector:
matchLabels:
app: ithomelab-api
template:
metadata:
labels:
app: ithomelab-api
spec:
containers:
- name: api
image: registry.gitlab.com/gurubear-ithome-13th/homelabapi:Release-v0.0.1
env:
- name: ASPNETCORE_ENVIRONMENT
value: "Production"
- name: TZ
value: "Asia/Taipei"
- name: ConnectionStrings
valueFrom:
configMapKeyRef:
name: apicm
key: api-day04-cm
ports:
- containerPort: 7777
將API運行起來後,確實有讀到
使用Port-forward 檢查看看有沒有正確顯示API出來。
kubectl port-forward ithomelab-api-deployment-7bb967b947-xqgpb 7777:7777 -n ithomelab
一切正常,所以如法炮製佈署Day06的react+nginx deployment,react-day06-deploy.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ithomelab-react-deployment
namespace: ithomelab
labels:
app: ithomelab-react
spec:
replicas: 1
selector:
matchLabels:
app: ithomelab-react
template:
metadata:
labels:
app: ithomelab-react
spec:
containers:
- name: react
image: registry.gitlab.com/gurubear-ithome-13th/homelabreact:Release-v0.0.1
env:
- name: TZ
value: "Asia/Taipei"
ports:
- containerPort: 80
最後將兩個deployment接出ClusterIP type的service,分別如下:
ithomelab-api-svc.yml
apiVersion: v1
kind: Service
metadata:
labels:
app: ithomelab-api
name: ithomelab-api-deployment
namespace: ithomelab
spec:
ports:
- port: 80
protocol: TCP
targetPort: 7777
selector:
app: ithomelab-api
sessionAffinity: None
type: ClusterIP
ithomelab-react-svc.yml
apiVersion: v1
kind: Service
metadata:
labels:
app: ithomelab-react
name: ithomelab-react-deployment
namespace: ithomelab
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: ithomelab-react
sessionAffinity: None
type: ClusterIP
檢查一下service&endpoint的關係
最後總結一下今天佈署的內容
突然想到提一下,因為這邊都是從public registry去pull image所以沒有權限的問題,如果要從private registry去pull的話就需要imagePullSecrets,而在gitlab上我習慣使用deploy tokens來做為帳密使用。