ConfigMap - with Nginx

Page content

Motivation

I want to mount Nginx configuration as ConfigMap.

The simplest example

Original

Here is the default /etc/nginx/conf.d/default.conf in Nginx Docker image (comment outs were removed.)

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Overwritte - return a message

I’ve changed location / to return the message Have a nice day!.

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    location / {
        return 200 "Have a nice day!";
        add_header Content-Type text/plain;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Deploy the ConfigMap

$ kubectl create configmap my-nginx-config --from-file=default.conf
configmap/my-nginx-config created
$ kubectl get configmap
NAME              DATA   AGE
my-nginx-config   1      8m26s

Apply to Pods (containers)

Here is a sample Deployment file.

kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2 # tells deployment to run 2 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.19.3
        ports:
        - containerPort: 80
        volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx/conf.d/
          readOnly: true
      volumes:
      - name: nginx-config
        configMap:
          name: my-nginx-config #<-Here is your ConfigMap name

Deploy and check (Service is deployed already).

kubectl apply -f nginx-deployment.yml

Let’s try to access the container by kubectl exec --stdin --tty {{ your_pod_name }} -- /bin/bash and see /etc/nginx/conf.d/default.conf. It is overwritten!!