package main
import(
"net/http"
"os"
"log"
"github.com/gorilla/mux"
"fmt"
)
func NameHandler(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Name: %v\n", vars["name"])
}
func main(){
port := os.Getenv("K_PORT")
if port == "" {
log.Fatal("Must Specify K_PORT Env Var")
}
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w,"hi..")
})
r.HandleFunc("/name/{name}/", NameHandler)
log.Fatal(http.ListenAndServe(":"+string(port),r))
}
Dockerfile:
FROM localhost:5000/golang:1.16-alpine as builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o ./hello-there
from alpine
COPY --from=builder /app/hello-there /bin/hello-there
RUN adduser -D appuser && chown appuser /bin/hello-there
USER appuser
CMD [ "/bin/hello-there" ]
sa.yaml:
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp
labels:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
deloyment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
labels:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
template:
metadata:
labels:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
spec:
serviceAccountName: myapp
securityContext:
{}
containers:
- name: myapp
securityContext:
{}
image: "192.168.56.11:5000/api_name:0.0.1"
imagePullPolicy: IfNotPresent
env:
- name: K_PORT
value: "3000"
ports:
- name: http
containerPort: 3000
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{}
Service examples:
kubectl expose deployment hello-world --type=NodePort --name=example-service
NodePort Svc
apiVersion: v1
kind: Service
metadata:
name: myapp
labels:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
spec:
type: NodePort
ports:
- nodePort: 31801
targetPort: 3000
port: 3000
protocol: TCP
selector:
app.kubernetes.io/name: myapp
app.kubernetes.io/branch: main
Ingress:
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm upgrade --install ingress-nginx ingress-nginx \
--repo https://kubernetes.github.io/ingress-nginx \
--namespace ingress-nginx --create-namespace
kubectl wait --namespace ingress-nginx \
--for=condition=ready pod \
--selector=app.kubernetes.io/component=controller \
--timeout=120s
kubectl create ingress demo --class=nginx --rule="www.myapp.io/*=myapp:3000"
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: demo
namespace: default
spec:
ingressClassName: nginx
rules:
- host: www.myapp.io
http:
paths:
- backend:
service:
name: myapp
port:
number: 3000
path: /
pathType: Prefix
status:
loadBalancer: {}
Test:
curl -H'Host: www.myapp.io' http://localhost:30578/name/{kurtis}/