Search code examples
kubernetesdeploymentservice

I can't curl nginx which I deployed on k8s cluster


my deployment yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels: 
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

my service yaml:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

enter image description here

enter image description here

and then I curl 10.104.239.140, but get an error curl: (7) Failed connect to 10.104.239.140:80; Connection timed out

Who can tell me what's wrong?


Solution

  • welcome to SO. That service you've deployed is of type ClusterIP which means it can only be accessed from within the cluster. In your case, it seems you're trying to access it from outside the cluster and thus the connection timed out.

    What you can do is, deploy a service of type NodePort or LoadBalancer to access it from outside the cluster. You can read more about different service types here.

    You're service would end up something like this:

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx-service
    spec:
      type: NodePort      ## or LoadBalancer(supported by Cloud providers like AWS)    
      selector:
        app: nginx
      ports:
      - protocol: TCP
        port: 80
        targetPort: 80
        # Optional field
        # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
        nodePort: 30001