Name-based Virtual Hosting in Kubernetes¶
Name-based virtual hosting allows a single IP address to host multiple domains or hostnames. In the context of Kubernetes, this functionality is primarily handled by the Ingress controller^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
Mechanism¶
Ingress operates as a higher-level [[LoadBalancer]] that sits above standard [[Services]]. Instead of exposing a different port for every Service—which results in managing numerous port mappings—Ingress统一监听 standard HTTP (port 80) and HTTPS (port 443) ports^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md]. It inspects the Host header of incoming HTTP requests to determine which backend Service should receive the traffic^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
Configuration¶
Virtual hosting is configured by defining rules within an Ingress resource manifest. Each rule specifies a host value and maps it to a specific backend service^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
For example, the configuration below routes traffic based on the hostname:
- Requests to
foo.comare routed tofoo-service. - Requests to
bar.comare routed tobar-service^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
spec:
ingressClassName: nginx
rules:
- host: foo.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: foo-service
port:
number: 8000
- host: bar.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: bar-service
port:
number: 8000
Local Testing¶
When implementing Name-based Virtual Hosting in a local development environment (such as Docker Desktop), the configured hostnames (e.g., foo.com, bar.com) must be resolved to the local loopback address^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
This is typically achieved by adding entries to the /etc/hosts file^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
# /etc/hosts
127.0.0.1 foo.com
127.0.0.1 bar.com
Once mapped, tools like curl can be used to verify that the Ingress Controller correctly routes requests to the specific Services based on the hostname^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md].
Related Concepts¶
- [[Simple fanout]]
- Ingress
- [[Service]]
- SSL Termination
Sources¶
^[400-devops__06-Kubernetes__k8s-ithelp__Day9__README.md]