Use external services in Kubernetes
Example with external database services
Let's asume that we have a database server running outside of our Kubernetes cluster, and we want to connect to it from our pods.
For the example, our server is running on db.example.com
, to import the external database service, we can create a Service
resource in Kubernetes that points to the external database server.
apiVersion: v1
kind: Service
metadata:
name: external-db
spec:
type: ExternalName
externalName: db.example.com
When a service is created Kubernetes, an ip address is assigned to it, and and the Kurbernetes DNS service is populated with a A record to associate the service name with the ip address of the external database server. But when using an ExternalName
service, Kubernetes does not assign an ip address to the service, but instead creates a CNAME record in the DNS service that points to the external database server.
Whan an application in the cluster will make a dns lookup for the hostname external-db.svc.default.cluster
, the DNS service will aliases the hostname to db.example.com
, and the application will be able to connect to the external database server using the service name external-db
.
Same thing but without a dns external service
We can do the same thing for external service without using a dns but the ip address:
- create a service without a label selector
apiVersion: v1
kind: Service
metadata:
name: external-ip-servics
At this point. Kubernetes will allocate a virtual ip address to the service amd create a A record in the DNS service that points to the virtual ip address of the service. However, because there is no selector for the service, there will be no endpoints populated for the load balancer to redirect traffic to.
The user is responsible for creating the endpoints for the service, which can be done by creating an Endpoints
resource.
apiVersion: v1
kind: Endpoints
metadata:
name: external-ip-service
subsets:
- addresses:
- ip: 192.168.1.74
ports:
- port: 5432
name: postgres
If you have more than one IP Address for redundancy, you can repeat them in the addresses
array. Once the Endpoints
resource is created, the load balancer will start redirecting traffic to the specified IP addresses.
Because the user has assumed responsibility for keeping the IP address of the server up to date, you need to either ensure that it never changes or make sure that some automated process updates the Endpoints record.
Limitations
External services in Kubernetes have one significant restriction:
- they do notperfom anuy health checking.
- The user is responsible for ensuring that the endpoints or DNS name is valid and reachable.