Communicate two microservices in a Kubernetes cluster
First we create a deployment and a service to communicate to
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp1
spec:
replicas: 1
selector:
matchLabels:
app: webapp1
template:
metadata:
labels:
app: webapp1
spec:
containers:
- name: webapp1
image: katacoda/docker-http-server:latest
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: web-app-service
spec:
selector:
app: webapp1
ports:
- protocol: TCP
port: 80
Save as web-app-service.yaml
and run the following command
kubectl create -f web-app-service.yaml
When a Pod is executed inside a Node, the kubelet adds to it a set of environment variables that include the HOST and PORT of every running service:
{SVCNAME}_SERVICE_HOST` y `{SVCNAME}_SERVICE_PORT
.
If our service name is web_app_service
then we get the environment variables: WEB_APP_SERVICE_SERVICE_HOST
and WEB_APP_SERVICE_SERVICE_PORT
Then we can pass these as envrionment variables of the second service, and the cluster will keep them actualized, even if the HOST and/or PORT changes.
Reference Links
Last updated