Nginx with ConfigMap Volume Mount
Deploy Nginx with a custom configuration file stored in a Kubernetes ConfigMap, mounted as a volume into the container at /etc/nginx/conf.d/.
Detailed Explanation
Custom Nginx Config via ConfigMap
Rather than building a custom Docker image for every Nginx configuration change, you can store the config in a Kubernetes ConfigMap and mount it into the container. This separates configuration from the container image, following the 12-factor app methodology.
Key Configuration
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-custom
labels:
app: "nginx-custom"
spec:
replicas: 2
template:
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- name: http
containerPort: 80
volumeMounts:
- name: nginx-config
mountPath: /etc/nginx/conf.d
readOnly: true
resources:
requests:
cpu: "50m"
memory: "64Mi"
limits:
cpu: "200m"
memory: "128Mi"
volumes:
- name: nginx-config
configMap:
name: nginx-conf
Creating the ConfigMap
Before deploying, create the ConfigMap with your Nginx configuration:
kubectl create configmap nginx-conf \
--from-file=default.conf=./my-nginx.conf
Or define it in YAML:
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-conf
data:
default.conf: |
server {
listen 80;
location / {
proxy_pass http://backend:3000;
}
}
Mount Details
The volume mount replaces the entire /etc/nginx/conf.d/ directory with the contents of the ConfigMap. Each key in the ConfigMap becomes a file in the mounted directory. Using readOnly: true prevents the container from accidentally modifying the mounted config.
Hot Reloads
When you update the ConfigMap, Kubernetes eventually propagates the change to the mounted volume (this can take up to 1 minute by default). However, Nginx does not automatically reload its configuration. You need either a sidecar that watches for file changes and sends SIGHUP to Nginx, or a rolling restart of the deployment.
Use Case
Deploying Nginx as a reverse proxy or load balancer where the configuration needs to be changed independently of the container image, managed through ConfigMaps for GitOps workflows.