kubernetes - Use ports of other containers on the same pod for setting environment variables

2/25/2018

I want to communicate with containers which are in the same pod programmatically.

So,I decided to set the ports of the auxiliary containers (bar1-container and bar2-container in this example) as environment variables of the primary container (i.e. foo-container).

However, I could not figure out how to pass the exposed ports of the auxiliary ports can be implicitly in the .yaml file for my deployment configuration:

apiVersion:  apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: test-deployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: web
        tier: frontend
    spec:
      containers:
      # Only container to be exposed outside the pod
      - name: foo-container
        image: foo
        env:
        - name: BAR_1_PORT
          # HOW TO GET PORT HERE IMPLICITLY ???
          value: XXXX 
        - name: BAR_2_PORT
          # HOW TO GET PORT HERE IMPLICITLY ???
          value: XXXX
        ports:
        - name: https
          containerPort: 443
        - name: http
          containerPort: 80
      # SubContainer 1
      - name: bar1-container
        image: bar1
      # SubContainer 2
      - name: bar2-container
        image: bar2

I wonder if there is a way to use the ports like ${some-variable-or-so-here} instead of 5300, 80, 9000 or whichever port is exposed from the container.

P.S: I deliberately did not specify ports or containerPort values of auxiliary containers in the yaml configuatin above as they will not be exposed outside the pod.

-- vahdet
docker
environment-variables
kubernetes
yaml

1 Answer

2/25/2018

You are mixing containers, pods and services here. If you have multiple containers within the same pod, to communicate between them, you need no service at all, also you need to pointing it to a hostname as they share the same network namespace. All you need to do is to connect to localhost on port that your particular service is listening on. For example you can have nginx container (listening on 80) connect to the second containers service of php-fpm via localhost:9000.

-- Radek 'Goblin' Pieczonka
Source: StackOverflow