OpenShift Cheatsheet for DevOps

Whether you're a beginner exploring OpenShift for the first time or an experienced user looking for a quick reference, this cheatsheet is designed to give you a CheatSheet of OpenShift oc CLI commands, concepts, and best practices — updated for current OpenShift releases (4.19/4.21). From managing Pods and Services to setting up Routes and exploring deployment strategies, we've got you covered.

openshift tutorial cheatsheet

DeploymentConfig is deprecated — prefer Deployment

Several commands below still reference dc (DeploymentConfig), OpenShift's original, platform-specific deployment resource. It still works today, but Red Hat has deprecated it in favor of the standard Kubernetes Deployment object, which is what oc new-app creates by default on current OpenShift versions. We've kept the dc-based commands here since plenty of existing clusters and pipelines still use them, but for anything new, swap dc/name for deployment/name in the equivalent commands (e.g. oc scale deployment/nginx --replicas=2, oc set probe deployment/nginx ...) and use oc rollout restart deployment/name instead of oc rollout latest, which is DeploymentConfig-specific.

Login and Configuration

Firstly, let's check the most common commands for login and configuration in OpenShift:

#login with a user
oc login https://192.168.99.100:8443 -u developer -p developer

#login as system admin
oc login -u system:admin

#User Information
oc whoami

#Show the API server URL you're currently connected to
oc whoami --show-server

#Print your current login token (useful for scripting/CI)
oc whoami --show-token

#View your configuration
oc config view

#Update the current context to have users login to the desired namespace:
oc config set-context $(oc config current-context) --namespace=<project_name>

# List OAuth Access Tokens
oc get useroauthaccesstokens

# Check the OpenShift Container Platform (cluster) version
oc get clusterversion

# Check oc client and server version
oc version

Basic Commands

Secondly, here is a list of basic commands to manage Pods and create applications with Templates:

#Create a new app from a GitHub Repository
oc new-app https://github.com/sclorg/cakephp-ex

#New app from a different branch
oc new-app --name=html-dev nginx:1.10~https://github.com/joe-speedboat/openshift.html.devops.git#mybranch

#Create objects from a file:
oc create -f myobject.yaml -n myproject

#Delete objects contained in a file:
oc delete -f myobject.yaml -n myproject

#Create or merge objects from file
oc apply -f myobject.yaml -n myproject

#Update existing object
oc patch svc mysvc --type merge --patch '{"spec":{"ports":[{"port": 8080, "targetPort": 5000 }]}}'

#Monitor Pod status
watch oc get pods

#Get a Specific Item (podIP) using a Go template
oc get pod example-pod-2 --template='{{.status.podIP}}'

#Gather information on a project's pod deployment with node information
oc get pods -o wide

#Hide inactive Pods
oc get pods --field-selector=status.phase=Running

#Display all resources
oc get all,secret,configmap

#Get the OpenShift Console Address
oc get -n openshift-console route console

#Get the Pod name from the Selector, then rsh into it
POD=$(oc get pods -l app=myapp -o name)
oc rsh $POD

#Exec a single command in a running pod
oc exec $POD -- $COMMAND

# Creates a pod for the container image "fedora" and executes commands with it
oc run fedora-pod --image=fedora --restart=Never --command -- sleep infinity

#Copy from local folder byteman-4.0.12 into Pod wildfly-basic-1-mrlt5 under the folder /opt/wildfly
oc cp ./byteman-4.0.12 wildfly-basic-1-mrlt5:/opt/wildfly

Note: the old --show-all=false flag used in earlier versions of this cheatsheet to hide completed/failed Pods was removed years ago; use a --field-selector as shown above, or oc get pods --field-selector=status.phase!=Succeeded,status.phase!=Failed to combine both filters.

Image Streams

Here is how to list and import ImageStreams on OpenShift:

#List available Image Streams for the openshift project
oc get is -n openshift

#Import an image from an external registry
oc import-image my-imagestream --from=registry.access.redhat.com/ubi9/ubi -n openshift --confirm

#List available Image Streams and templates
oc new-app --list

Templates Management

Next, here is how to process Templates:

# Deploy resources contained in a template
oc process -f template.yaml | oc create -f -

#List parameters available in a template
oc process --parameters -f template.yaml

ConfigMap and Secrets

Create a ConfigMap/Secret from a file:

oc create configmap my-config --from-file=config.properties

oc create secret generic my-secret --from-file=secret.key

Create a ConfigMap/Secret from literals:

oc create configmap my-config --from-literal=foo=bar --from-literal=baz=qux
oc create secret generic my-secret --from-literal=secret.key=value

Set a ConfigMap/Secret in a deployment:

oc set env deployment/my-deployment --from configmap/my-config
oc set env deployment/my-deployment --from secret/my-secret

How to display a ConfigMap content:

oc get cm/my-config -o yaml

Setting Environment Variables

Then, here is how to set environment variables on Deployments/Build Configs and list them:

# Update deployment 'registry' with a new environment variable
oc set env deployment/registry STORAGE_DIR=/local

# List the environment variables defined on a build config 'sample-build'
oc set env bc/sample-build --list

# List the environment variables defined on all pods
oc set env pods --all --list

# Import environment from a secret
oc set env --from=secret/mysecret deployment/myapp

Editing

Then, here is a list of commands that can assist you in editing resources with just the command line:

# Edit the build configuration
oc edit bc/devfile-sample-python-basic-git

# Change the default editor to vim
export EDITOR=vi

Resources and Operators

Here is a list of commands to inspect the resources available in an OpenShift cluster:

# Prints the supported API resources, including resource names, available shortnames, and API versions
oc api-resources

# Limit the output of the api-resources command to namespaced resources
oc api-resources --namespaced

# List the resource types that the apps API group provides
oc api-resources --api-group apps

# List the operators that users installed in the OpenShift cluster
oc get subscriptions -A

# List the cluster operators installed by default
oc get clusteroperators

Note: oc get operators is still available, but for checking the actual health/version of installed Operators via OLM, oc get subscriptions -A and oc get csv -A (ClusterServiceVersions) give you more actionable detail.

WildFly Application Example on OpenShift

Please refer to this article: How to run WildFly on Openshift

Create an App from a Project with Dockerfile

Next, here is how to create an app from a Dockerfile using a Binary Build:

oc new-build --binary --name=mywildfly -l app=mywildfly

oc patch bc/mywildfly -p '{"spec":{"strategy":{"dockerStrategy":{"dockerfilePath":"Dockerfile"}}}}'

oc start-build mywildfly --from-dir=. --follow

oc new-app --image-stream=mywildfly

oc expose svc/mywildfly

How to Manage Nodes

#Get Nodes list
oc get nodes

#Check on which Node your Pods are running
oc get pods -o wide

#Schedule an application to run on a specific Node
oc patch deployment myapp -p '{"spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname": "ip-10-0-0-74.acme.compute.internal"}}}}}'

#List all pods running on a Node
oc adm manage-node node1.local --list-pods

#Mark a Node unschedulable (modern replacement for --schedulable=false)
oc adm cordon node1.local

#Mark a Node schedulable again
oc adm uncordon node1.local

#Safely evict all Pods from a Node before maintenance
oc adm drain node1.local --ignore-daemonsets --delete-emptydir-data

#Add a label to a Node
oc label node node1.local mylabel=myvalue

#Remove a label from a Node
oc label node node1.local mylabel-

#Check if a Node has associated Taints:
oc describe node <nodename> | grep Taints

#Remove Taint NoSchedule from node "master"
oc adm taint node master node-role.kubernetes.io/master:NoSchedule-

How to Manage Storage

#Create a PersistentVolumeClaim and attach it to a Deployment's volume mount
oc set volume deployment/file-uploader --add --name=my-shared-storage \
    -t pvc --claim-mode=ReadWriteMany --claim-size=1Gi \
    --claim-name=my-shared-storage --claim-class=ocs-storagecluster-cephfs \
    --mount-path=/opt/app-root/src/uploaded

#List storage classes
oc get sc

Build Management

#Manual build from source
oc start-build ruby-ex

#Manual build from source and follow logs
oc start-build ruby-ex -F

#Stop a build that is in progress
oc cancel-build <build_name>

#Changing the log level of a build:
oc set env bc/my-build-name BUILD_LOGLEVEL=[1-5]

# Wait for the build to complete, up to 600 seconds
oc wait --for=condition=complete --timeout=600s build/myapp-1

How to Manage Deployments

#Manual deployment (DeploymentConfig-specific; for a Deployment use "oc rollout restart deployment/name" instead)
oc rollout latest ruby-ex

#Pause automatic deployment rollout
oc rollout pause deployment/nginx

# Resume automatic deployment rollout
oc rollout resume deployment/nginx

#Define resource requests and limits
oc set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi

#Define liveness and readiness probes
oc set probe deployment/nginx --readiness --get-url=http://:8080/healthz --initial-delay-seconds=10
oc set probe deployment/nginx --liveness --get-url=http://:8080/healthz --initial-delay-seconds=10

#Scale the number of Pods to 2
oc scale deployment/nginx --replicas=2

#Define a Horizontal Pod Autoscaler (HPA)
oc autoscale deployment/nginx --min=2 --max=4 --cpu-percent=10

Managing Routes

#Create a route
oc expose service ruby-ex

# Create a Route and expose it through a custom hostname
oc expose service ruby-ex --hostname=ruby-ex.apps.example.com

# Read the Route Host attribute
oc get route my-route -o jsonpath --template="{.spec.host}"

# Forward traffic from pod "myphp" from local port 8080 to the pod's port 8080
oc port-forward pod/myphp 8080:8080

Managing Services

#Make a service idle. It automatically boots the Pods back up on next access:
oc idle ruby-ex

#Read a Service ClusterIP
oc get services rook-ceph-mon-a --template='{{.spec.clusterIP}}'

Resource Usage

# List memory and CPU usage of all Pods in the cluster; --sum prints the total
oc adm top pods -A --sum

# List resource usage of the containers in Pod "mypod" in namespace "example"
oc adm top pods mypod -n example --containers

# Resource consumption per Node
oc adm top node

# List of all resources, their status, and their types in namespace "example"
oc get all -n example --show-kind

# Per-container resource consumption on the node (requires "cri-tools")
crictl stats

Clean Up Resources

#Delete all resources
oc delete all --all

#Delete resources for one specific app
oc delete services -l app=ruby-ex
oc delete all -l app=ruby-ex

#Clean up old container images on nodes
#Keeping up to three tag revisions, and keeping resources (images, image streams, pods) younger than sixty minutes:
oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m

#Pruning every image that exceeds defined limits:
oc adm prune images --prune-over-size-limit

Jobs

# Create a simple Job
oc create job hello --image=alpine -- echo "Hello World"

# Create a CronJob that prints "Hello World" every minute
oc create cronjob hello --image=alpine --schedule="*/1 * * * *" -- echo "Hello World"

Note: oc is fully kubectl-compatible, so both oc create job and kubectl create job work identically against an OpenShift cluster — the examples above use oc throughout simply for consistency with the rest of this cheatsheet.

OpenShift Container Platform Troubleshooting

#Inspect all resources in a namespace (produces a resource tree in YAML files)
oc adm inspect ns/mynamespace

#Run cluster diagnostics
oc adm diagnostics

#Collect must-gather (the standard first step Red Hat Support will ask for)
oc adm must-gather

#Check status of the current project
oc status

#Get events for a project sorted by timestamp
oc get events --sort-by=.metadata.creationTimestamp

#Get events of type Warning
oc get ev --field-selector type=Warning -o jsonpath='{.items[].message}{"\n"}'

# Get the logs of the myrunning-pod-2-fdthn pod
oc logs myrunning-pod-2-fdthn

# Follow the logs of the myrunning-pod-2-fdthn pod
oc logs -f myrunning-pod-2-fdthn

# Tail the last 50 lines of logs of the myrunning-pod-2-fdthn pod
oc logs myrunning-pod-2-fdthn --tail=50

#Check the integrated image registry logs (namespace/pod name will vary by cluster)
oc logs -n openshift-image-registry deployment/image-registry

# Create a temporary debug pod on a node
oc debug node/master01

Security

#Create a secret from the CLI
oc create secret generic oia-secret --from-literal=username=myuser --from-literal=password=mypassword

# Use the secret as env vars in a deployment
oc set env deployment/myapp --from secret/oia-secret

# You can also mount the Secret as a Volume
oc set volumes deployment/myapp --add --name=secret-volume --mount-path=/opt/app-root/ --secret-name=oia-secret

Managing User Roles

oc adm policy add-role-to-user admin oia -n python
oc adm policy add-cluster-role-to-user cluster-reader system:serviceaccount:monitoring:default
oc adm policy add-scc-to-user anyuid -z default

Misc Commands

#List installed operators (ClusterServiceVersions)
oc get csv -A

#Show your OpenShift username in the shell prompt
function ps1(){
   export PS1='[\u@\h($(oc whoami -c 2>/dev/null|cut -d/ -f3,1)) \W]\$ '
}

oc export was removed — don't rely on it

Older versions of this cheatsheet included oc export is,bc,dc,svc --as-template=app.yaml and a backup script built around oc export -o yaml. The oc export command was removed years ago (it existed only in OpenShift 3.x); running it today returns "unknown command". For a similar quick dump, use oc get <resources> -o yaml > backup.yaml and manually strip cluster-specific fields (resourceVersion, uid, status, etc.) before reapplying elsewhere. For real backup/restore and disaster recovery, use a dedicated tool such as Velero, which is what Red Hat itself recommends for OpenShift today rather than any built-in oc export mechanism.

Conclusion: As you conclude your journey through this OpenShift cheatsheet, you've equipped yourself with valuable insights and quick references to navigate the world of container orchestration on current OpenShift releases. OpenShift empowers you to build, deploy, and scale applications with efficiency and confidence.

Frequently Asked Questions

Is DeploymentConfig still supported in current OpenShift?

It still works, but it's deprecated in favor of the standard Kubernetes Deployment object, which is what oc new-app creates by default today. For any new application, use deployment/name instead of dc/name in the equivalent commands.

Why does oc export return "unknown command"?

Because it was removed from the oc CLI years ago (it only existed in OpenShift 3.x). Use oc get <resources> -o yaml for a quick manual dump, or a dedicated tool like Velero for real backup and disaster recovery.

What replaced oc adm manage-node --schedulable=false?

oc adm cordon <node> to mark a node unschedulable, and oc adm uncordon <node> to bring it back. Pair cordon with oc adm drain <node> when you need to safely evict running Pods before maintenance.

Can I use kubectl instead of oc on OpenShift?

Yes, for anything that's standard Kubernetes API (Deployments, Services, ConfigMaps, Jobs, etc.) kubectl works identically to oc. You need oc specifically for OpenShift-only resources and commands: Routes, ImageStreams, BuildConfigs/DeploymentConfigs, oc adm cluster-admin subcommands, and oc login's OAuth-based authentication flow.

How do I check which OpenShift version my cluster is running?

Run oc get clusterversion for the cluster's OpenShift version, or oc version to see both the oc client version and the server version side by side.

What's the recommended way to back up OpenShift resources today?

Use Velero for anything beyond ad-hoc YAML dumps — it handles both Kubernetes/OpenShift object state and, with the right plugin, persistent volume data, and supports scheduled backups and cross-cluster restore, none of which the old oc export command ever provided.


Recommended Articles

Deploy Java EE Application on Openshift with Custom Modules and CLI Commands

Learn how to deploy a Java EE application on Openshift, including custom modules and running CLI commands as part of the build process.

Optimizing Memory Constraints in OpenShift Using Advanced Commands

Learn how to resolve 'Insufficient memory' errors in OpenShift with expert tips and commands.

Mastering A/B Deployments on OpenShift PaaS with AB Deployments

Learn how to configure A/B deployments on OpenShift PaaS to balance traffic between multiple applications, using round-robin strategy and equal percentages of traffic.

How to Configure and Use Openshift Metrics for Paas Monitoring

Learn how to enable metrics on Openshift Origin and view or export them using Heapster, Hawkular Metrics, and Cassandra. Start your Openshift cluster with metrics enabled in just a few steps.