Sharing the service between namespaces in Kubernetes
When we want to access the Kubernetes service from another namespace in the scope of our cluster we could use the external name of that service. Bellow, I want to describe a little use case that I’m using in development.
Cluster
Let’s imagine that we have two independent applications located in a dedicated namespace. I will call these namespaces first-app
, second-app
.
Also, each of them requires to use of a database that is located in the namespace with a name shared
.
Solution
First of all, let’s create a service in Kubernetes with the type ExternalName
which will consume the deployment which we want to share, in a particular case that is database Postgres.
apiVersion: v1
kind: Service
metadata:
name: postgress-server
namespace: shared
spec:
ports:
- protocol: TCP
port: 5432
targetPort: 5432
type: ExternalName
externalName: postgress-server.shared.svc.cluster.local
Let me describe what is going on here:
- metadata.namespace → contains the name of namespace where we want to create that service;
- spec.type → defines the type of service we create;
- spec.externalName → defines the external name which we want to use from other services.
- [metadata.name].[metadata.namespace].[svc - share resource].[cluster]
As a result, we have to use instead of localhost:5432
the postgress-server.shared.svc.cluster.local:5432
host.
p.s. Hope it will be a useful note for someone. If you will have some questions, feel free to ask in the comments.