Kubernetes: Declarative vs Imperative (Nginx Example on Minikube)

In this post, I am going to run a Nginx example on Minikube in two ways:

1. declarative: kubectl apply -f [yaml]

2. imperative: kubectl create & expose


declarative: kubectl apply -f [yaml]

With a declarative way, you can define the resources as yamls and apply them.

This is preferable in a long run, but could be tedious if you just want to run it as a test.

% cat deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx

% cat service.yaml

apiVersion: v1

kind: Service

metadata:

  labels:

    app: nginx

  name: nginx

spec:

  ports:

  - port: 80

    protocol: TCP

    targetPort: 80

  selector:

    app: nginx

  type: NodePort

% kubectl apply -f deploy.yaml

% kubectl apply -f service.yaml


open nginx

% minikube service nginx

...

| default   | nginx |             | http://127.0.0.1:56930 |

...

🎉  Opening service default/nginx in default browser...



imperative: kubectl create & expose

With an imperative way, you can use the methods of kubectl to create the same resources above.

This is useful to save some time, especially during an exam like CKA.

% kubectl create deploy nginx --image=nginx

% kubectl expose deploy nginx --type=NodePort --port=80

You can also use dryrun and output option to create a yaml.

This way, you can take an advantage of both declarative & imperative ways.

% kubectl create deploy nginx --image=nginx --dry-run=client -o yaml > deploy.yaml

% vim deploy.yaml

% kubectl apply -f deploy.yaml


Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

PyCharm: Quick Start