简体   繁体   中英

Kubernetes get pod's full name inside tomcat container in Java

Tried to get the pod name inside the Tomcat container at startup. Already exposed the pod's full name as an environment variable using the Kubernetes Downward API as below in search.yaml file ( only a portion of the file attached).

apiVersion: apps/v1
kind: Deployment
metadata:
name: search
namespace: dev
labels:
    app: search
spec:
replicas: 1
selector:
    matchLabels:
    app: search
template:
    metadata:
    labels:
        app: search
    spec:
    hostname: search-host
    imagePullSecrets:
    - name: regcred
    containers:
    - name: search-container
        image: docker.test.net/search:develop-202104070845
        env:
        - name: MY_POD_NAME
        valueFrom:
            fieldRef:
            fieldPath: metadata.name
        ports:
        - containerPort: 8080
        resources:
        requests:
            memory: "2048Mi"
            cpu: "1"
        limits:
            memory: "2048Mi"
            cpu: "2"
        env:
        - name: SERVER_GROUP
        value: "SEARCH"
        - name: MIN_TOMCAT_MEMORY
        value: "512M"
        - name: MAX_TOMCAT_MEMORY
        value: "5596M"
        - name: DOCKER_TIME_ZONE
        value: "Asia/Colombo"
        - name: AVAILABILITY_ZONE
        value: "CMB"

After running the pod this environment variable is available in docker level.

Pod details

NAME                        READY    STATUS    RESTARTS      AGE
search-56c9544d58-bqrxv      1/1     Running      0          4s

Pod environment variable for pod name

POD_NAME=search-56c9544d58-bqrxv

When accessed this as below in Tomcat container's java code in a jar called BootsTrap.jar and it returned as null .

String dockerPodName = System.getenv( "POD_NAME" );

Is it because the pod is not up and running before the tomcat container initialized or accessing the environment variable in Java is incorrect or is there another way of accessing pod's environment variable through java.

You are setting MY_POD_NAME as environment variable, but do the lookup for POD_NAME . Use the same name in the Java code and the deployment.

Note: Your YAML seems to have wrong indentation, I assume that this is just a copy-paste artifact. If that is not the case, it could lead to rejected changes of the deployment since the YAML is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM