How create service on minikube with yaml configuration,which accessible from host?

Viewed 5781

How correct write yaml configuration for kubernetes pod and service in minikube cluster with driver on docker with one requirement: 80 port of container must be accessible from host machine. Solution with nodePort doesn't work as excepected:

 type: NodePort 
 ports:
  - port: 80
    targetPort: 8006
  selector:
    app: blogapp

Label app: blogapp set on container. Can you show correct configuration for nginx image for example with port accessible from host.

2 Answers

You should create a Kubernetes deployment instead of creating a NodePort. Once you create the deployment(which will also create a ReplicaSet and Pod automatically), you can expose it. The blogapp will not be available to the outside world by default, so you must expose it if you want to be able to access it from outside the cluster.

Exposing the deployment will automatically create a service as well.

deployment.yml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: blogapp
  labels:
    app: blogapp
spec:
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: blogapp
    spec:
      containers:
      - image: <YOUR_NGINX_IMAGE>
        name: blogapp
        ports:
        - containerPort: 8006
        resources: {}
      restartPolicy: Always
status: {}

Create the deployment

kubectl create -f deployment.yml

Expose the deployment

kubectl expose deployment blogapp --name=blogapp --type=LoadBalancer --target-port=8006

Get the exposed URL

minikube service blogapp --url

You can use the below configuration:

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: blog-app-server-instance
  labels:
    app: blog-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: blog-app
  template:
    metadata:
      labels:
        app: blog-app
    spec:
      containers:
      - name: blog-app-server-instance
        image: blog-app-server
        ports:
        - containerPort: 8006
---
apiVersion: v1
kind: Service
metadata:
  name: blog-app-service
  labels:
    app: blog-app
spec:
  selector:
    app: blog-app
  type: NodePort
  ports:
  - port: 80
    nodePort: 31364
    targetPort: 8006
    protocol: TCP
    name: http

I guess you were missing spec.ports[0].nodePort.

Related