Using “oc patch” command in multi-container Pods

I recently ran into a scenario wherein I had to add port in a deploymentConfig(DC) file having multiple containers. “oc edit” is a quite handy command but it will open an editor thereby not useful when automating the updation. Let us take a look at the DC file and apply “oc patch” command on it to update certain fields.

apiVersion: v1
kind: DeploymentConfig
metadata:
name: test-deploy
labels:
app: test-deploy
spec:
replicas: 1
strategy:
type: Rolling
template:
metadata:
labels:
app: test-deploy
name: test-deploy
spec:
containers:
- name: my-first-image
image: image1
ports:
- containerPort: 8080
protocol: TCP
- name: my-second-image
image: image2
env:
- name: JAVA_TOOL_OPTIONS
value: "-Xms768m -Xmx1g"

JSON equivalent of above yaml file will like:

{ “apiVersion”: “v1”, “kind”: “DeploymentConfig”, “metadata”: { “name”: “test-deploy”, “labels”: { “app”: “test-deploy” } }, “spec”: {“replicas”: 1,“strategy”: {"type": “rolling”},“template”: {“metadata”: {“labels”: {“app”: “test-deploy”}, “name”: “test-deploy”}, “spec”: {“containers”: [{ “name”: “my-first-image”, “image”: “image1”, “ports”: [{ “containerPort”: “8080”, “protocol”: “TCP”}] }, { “name”: “my-second-image”, “image”: “image2”, “env”: [{ “name”: “JAVA_TOOL_OPTIONS”, “value”: “\"-Xms768m -Xmx1g\"” }] }] } }

Lets create the DC with below command:

    oc create -f my-dc.yml

Now if we wish to edit the DC and append port to second image as shown below, “oc patch” will come into action:

      - name: my-second-image
image: image2
env:
- name: JAVA_TOOL_OPTIONS
value: "-Xms768m -Xmx1g"
ports:
- containerPort: 9090
protocol: TCP

The command will be as follows:

oc patch dc test-deploy -p '{"spec": {"template": {"spec": {"containers": [{"name": "my-second-image","ports": [{"containerPort": 9090,"protocol": "TCP"}]}]}}}}'

Now in order to modify environment variables value to -Xms821m -Xmx1g for second container, we can use below command:

oc patch dc test-deploy -p '{"spec": {"template": {"spec": {"containers": [{"name": "my-second-image","env": [{"name": "JAVA_TOOL_OPTIONS","value": “\"-Xms821m -Xmx1g\"”}]}]}}}}'