Kubernetes connect service and deployment

4/11/2020

I am wondering what to specify in a separate deployment in order to have it access a DB deployment/service. Here is the DB deployment/service:

apiVersion: v1
kind: Service
metadata:
  name: oracle-db
  labels:
    app: oracle-db
spec:
  ports:
  - name: oracle-db
    port: 1521
    protocol: TCP
    targetPort: 1521
  selector:
    app: oracle-db
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: oracle-db-depl
  labels:
    app: oracle-db
spec:
  selector:
    matchLabels:
      app: oracle-db
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: oracle-db
    spec:
      containers:
      - name: oracle-db
        image: oracledb:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 1521
        env:
          ...

How exactly do I specify the connection in the separate deployment? Do I specify the oracle-db service name somewhere? So far I specify a containerPort in the container.

-- user1394
kubernetes

2 Answers

4/11/2020

If the other app deployment is in the same namespace you can refer to the oracle service by oracle-db. Here is an example of a word-press application using oracle.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress
  labels:
    app: wordpress
spec:
  selector:
    matchLabels:
      app: wordpress
      tier: frontend
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: wordpress
        tier: frontend
    spec:
      containers:
      - image: wordpress:4.8-apache
        name: wordpress
        env:
        - name: WORDPRESS_DB_HOST
          value: oracle-db
        ports:
        - containerPort: 80
          name: wordpress

As you can see oracle service is being referred by oracle-db as an environment variable.

If the service is in different namespace than the app deployment then you can refer to it as oracle-db.namespacename.svc.cluster.local

https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/

-- Arghya Sadhu
Source: StackOverflow

4/11/2020

Services in Kubernetes are an "abstract way to expose an application running on a set of Pods as a network service." (k8s documentation)

You can access your pod by its IP and port that Kubernetes have given to it, but that's not a good practice as the Pods can die and another one will be created (if controlled by a Deployment/ReplicaSet). When the new one is created, a new IP will be used, and everything on your app will start to fail.

To solve this you can expose your Pod using a Service (as you already have done), and use service-name:service-port assigned to the Service to access your Pod. In this case, even if the Pod dies and a new one is created, Kubernetes will keep forwarding the traffic to the right Pod.

-- Juliano Costa
Source: StackOverflow