Search code examples
kuberneteskubectl

Kubernetes expose does not work from file


If I run command

kubectl expose deployments/some-app --type=NodePort

it works.

If I run command

kubectl apply -f expose.yml

Where the content of expose.yml is

apiVersion: v1
kind: Service
metadata:
  name: some-app
  labels:
    app: some-app
spec:
  type: NodePort
  ports:
    - port: 8080
  selector:
    app: some-app

I cannot reach the service.

What is the difference? Why the 2nd approach does not work?

EDIT: Use NodePort in the yml as well

EDIT: Result of command kubectl expose deployments/some-app --type=NodePort --dry-run -o yaml:

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: some-app
    type: spring-app
  name: some-app
spec:
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    name: some-app
  type: NodePort
status:
  loadBalancer: {}

Solution

  • In your expose command you use --type=NodePort, but in svc type=ClusterIP. If you want to see what expose command created then add --dry-run --o yaml at the end of the command. You should see like following.

    apiVersion: v1
    kind: Service
    metadata:
      labels:
        run: some-app
      name: some-app
    spec:
      ports:
      - port: 8080
        protocol: TCP
        targetPort: 8080
      selector:
        app: some-app
      type: NodePort
    

    NB: After discussion in comment, you need to ensure app: some-app exists on pod leve.