OpenShift commands

Command lines for oc, the OpenShift CLI, from the OpenShift Container Platform 4.22 documentation: the getting-started steps plus the developer and administrator command references, grouped by task. Names such as myapp, nginx or foo are the documentation's sample values; capitalised words such as CLUSTER_URL are placeholders. oc does everything kubectl does and adds logins, projects, builds, image streams and routes. A dc/ prefix targets a DeploymentConfig, deployment/ a standard Deployment. Certificate rotation, migration and catalog mirroring commands are left out.

171 commands in 14 sections. Checked row by row against Red Hat documentation on . Edited by Jay.

Logging in and identity 13

The Copy login command entry in the web console's user menu, top right, generates an oc login line that already holds your token and server.

Browser login with --web starts a local helper server over plain HTTP, so take care on workstations shared by several users.

CommandWhat it does
oc login -u user1Log in with a user nameoc then prompts for the server URL, whether to allow an untrusted certificate, and the password.
oc login API_SERVER_URL -u USERNAME -p PASSWORDLog in to a cluster APIThe server is the full API URL, for example https://api.my-cluster.example.com:6443, and no prompts follow.
oc login https://openshift1.example.com --token=ns7yVhuRNpDM9cgzfhhxQ7bM5s7N2ZVrkZepSRf4LC0Log in with an access tokenCopy login command in the web console's user menu generates this line with your own token and server.
oc login CLUSTER_URL --webLog in through a browserKeeps the token off the command line; if no browser window opens, follow the link oc prints.
oc login localhost:8443 --certificate-authority=/path/to/cert.crtLog in trusting a CA fileThe named certificate authority file is used to verify the server's certificate.
oc logoutLog out of the clusterThe token saved on the server is deleted and dropped from your local configuration file.
oc whoamiShow the logged-in user
oc whoami -cShow the active contextHandy after editing a context: every later oc call uses the context this prints.
oc auth whoamiShow your subject attributes
oc auth can-i create pods --all-namespacesCheck a permission everywhereTests the create verb on pods across all namespaces; swap verb and resource to check other actions.
oc auth can-i --list --namespace=fooList your allowed actionsPrints every action you may perform in namespace foo rather than testing a single one.
oc registry loginLog in to the internal registryTargets the cluster's integrated registry; add --registry and --auth-basic=USER:PASS for another registry.
oc create token myappRequest a service account tokenIssues an API credential for the myapp service account of the project in use; --duration sets its lifetime.

Projects and contexts 12

CommandWhat it does
oc new-project my-projectCreate projectoc switches to the new project straight away, as its Now using project output confirms.
oc new-project web-team-dev --display-name="Web Team Development" --description="Development project for the web team."New project with display name
oc project myappSwitch projectWorks for any project your user can already access; later commands then run there.
oc projectShow the current projectPrints the project in use together with the server it lives on.
oc projectsList projects
oc statusProject overviewSummarizes services, deployments and build configs of the project in use and how they connect.
oc status --suggestOverview with suggestionsAdds details about any problems oc identifies in the project to the summary.
oc config get-contextsList kubeconfig contexts
oc config use-context minikubeSwitch contextHere minikube is a context name; take the real names from oc config get-contexts.
oc config current-contextPrint the current context name
oc config viewShow the merged kubeconfigDisplays the configuration oc ends up using after combining every loaded file.
oc config view --raw > kubeconfigExport the kubeconfig to a fileWith --raw the file keeps certificate data and secrets; point KUBECONFIG at it and store it securely.

Viewing resources 15

Run inside a pod without a namespace option, oc works in the namespace of that pod.

Keep oc at the cluster's version: an older binary cannot run every command that OpenShift Container Platform 4.22 offers.

CommandWhat it does
oc get podsList podsOutput is a table of the pods in the project you are using.
oc get pods -o wideList pods with node namesThe wide format adds columns such as the pod IP and the node each pod runs on.
oc get allGet all resourcesShows services, deployments and the other object types of the project in one listing.
oc get pods --all-namespacesList pods in every namespace
oc get rc,servicesList several resource typesSeparate the resource types with commas to get one combined table.
oc get -o json pod web-pod-13je7Get one pod as JSON
oc get nodesList cluster nodes
oc describe pods/nginxDescribe podShows the details of the single pod named nginx; leave the name out to describe every pod.
oc describe pods -l name=myLabelDescribe pods by label
oc eventsList recent events
oc events --for pod/web-pod-13je7 --watchWatch events for one podLists the pod's recent events first, then keeps printing new ones until you stop it.
oc api-resourcesList API resource typesIncludes short names, API group and whether each type is namespaced.
oc versionShow client and server versionsCovers the oc binary and both API servers, so client and cluster versions can be compared.
oc version --clientShow only the client version
oc cluster-infoShow control plane addresses

Logs, shells and debugging 13

CommandWhat it does
oc logs cakephp-ex-1-deployView logsPrints a pod's log; add -c and a container name when the pod runs several containers.
oc logs -f pod/backend -c ruby-containerStream container logs-f keeps following the log as it grows; -c picks the container inside pod backend.
oc logs -f bc/openldapFollow the latest build logGiven a build config, oc shows the log of its most recent build.
oc logs -f dc/mysqlFollow the latest deployment logGiven a deployment config, oc streams the log of its newest deployment.
oc rsh fooRemote shellStarts an interactive shell in pod foo, using its first container unless -c picks another.
oc rsh foo cat /etc/resolv.confRun one command over rsh
oc exec mypod -- dateRun a command in a podEverything after -- is the command; it runs in the first container unless -c names one.
oc exec mypod -c ruby-container -i -t -- bash -ilInteractive shell with exec-i passes your input and -t puts the terminal in raw mode, giving a login shell in ruby-container.
oc exec deploy/mydeployment -- dateExec into a deployment's podoc chooses the deployment's first pod and that pod's first container.
oc debugStart a debug shellWithout arguments the debug pod runs the OpenShift tools image.
oc debug deploy/testDebug a running deploymentLaunches a separate new pod for debugging instead of entering the running ones.
oc debug node/master-1Debug a nodeMeant for cluster administrators; replace master-1 with the name of the node.
oc wait --for=condition=Ready pod/busybox1Wait until a pod is readyBlocks until the condition holds; add --timeout to give up after a set time.

Copying files and port forwarding 7

CommandWhat it does
oc rsync ./local/dir/ POD:/remote/dirSync a folder to a podPOD stands for the pod name, followed by the directory inside the container.
oc rsync POD:/remote/dir/ ./local/dirSync a pod folder locally
oc port-forward pod/mypod 5000 6000Forward local ports to a podEach listed port is opened locally and forwarded to the same port number in the pod.
oc port-forward pod/mypod 8888:5000Forward to a different pod portLOCAL:REMOTE form, so local port 8888 reaches port 5000 in the pod.
oc port-forward service/myservice 8443:httpsForward to a service portoc picks a pod behind the service and uses the target port of its port named https.
oc port-forward pod/mypod :5000Forward from a random local port
oc port-forward --address 0.0.0.0 pod/mypod 8888:5000Forward on all addresses

Creating applications 11

CommandWhat it does
oc new-app https://github.com/sclorg/cakephp-exApp from Gitoc detects the builder image, here PHP, then builds and deploys the application; oc status shows it.
oc new-app --image=myregistry.com/mycompany/mysql --name=privateNew app--image points at the registry image and --name replaces the default name of every generated object.
oc new-app centos/ruby-25-centos7~https://github.com/sclorg/ruby-ex.gitApp from builder image and sourceThe part before ~ is the builder image, the part after it the Git repository.
oc new-app https://github.com/openshift/ruby-hello-world#beta4App from a Git branchA # after the repository URL selects the branch to build, here beta4.
oc new-app https://github.com/youruser/yourgitrepo --context-dir=src/buildApp from a repository subfolder--context-dir names the directory inside the repository that holds the code.
oc new-app --template=ruby-helloworld-sample --param=MYSQL_USER=adminApp from a stored template--param overrides one of the template's parameter values.
oc new-app --search rubySearch for app sourcesFinds every template, image stream and container image whose name matches ruby.
oc new-app --listList templates and image streamsShows what oc new-app can start from without creating anything.
oc create deployment my-dep --image=busyboxCreate a deploymentAdd --replicas=3 or --port to set the pod count or the exposed container port.
oc run nginx --image=nginxStart a single pod
oc process -f template.json | oc create -f -Create objects from a template fileoc process renders the template, and the pipe hands the result to oc create.

Builds and images 14

CommandWhat it does
oc new-build . --image=repo/langimageCreate a build configUses the Git repository in the current folder, which needs a public remote, and the given builder image.
oc start-build hello-worldStart build
oc start-build hello-world --followBuild and watch the logsStays attached to the build log until it ends, successfully or not.
oc start-build hello-world --waitBuild and wait for the resultSuits scripts, because the exit code turns non-zero when the build fails.
oc start-build hello-world --from-dir=src/Build from a local folderSends what is in src/ as the input of the build.
oc start-build --from-build=hello-world-1Rerun an earlier build
oc cancel-build ruby-build-2Cancel a build
oc cancel-build ruby-build-2 --restartCancel and restart a buildStarts a replacement build with identical parameters right after cancelling.
oc import-image mystream --from=registry.io/repo/image:latest --confirmImport an image into a new streamCreates image stream mystream with tag latest from the external image.
oc import-image mystreamRefresh an imported imageRe-reads tag latest from its source for a stream that already exists.
oc tag openshift/ruby:2.0 yourproject/ruby:tipTag an image into another streamPoints yourproject/ruby:tip at the image currently tagged openshift/ruby:2.0.
oc tag --source=docker openshift/origin-control-plane:latest yourproject/ruby:tipTag an external image--source=docker marks the source as an external container image rather than a stream tag.
oc image info quay.io/openshift/cli:latestInspect a registry image
oc image mirror myregistry.com/myimage:latest myregistry.com/myimage:stableCopy an image to another tagThe same command copies between registries, and the target can also be a file:// directory.

Rollouts and scaling 16

CommandWhat it does
oc rollout status deployment/nginxRollout statusKeeps watching and reporting until the rollout of nginx is done.
oc rollout latest dc/nginxTrigger deployOnly for deployment configs: redeploys nginx with the newest images its image change triggers point to.
oc rollout undo deployment/abcRoll back a deploymentReturns deployment abc to its previous revision.
oc rollout undo daemonset/abc --to-revision=3Roll back to a given revision
oc rollout history deployment/abcShow rollout historyLists the revisions; add --revision=3 to see a single revision in detail.
oc rollout restart deployment/nginxRestart a deploymentWith --selector=app=nginx instead of a name, every deployment carrying that label restarts.
oc rollout pause deployment/nginxPause a rolloutRunning pods keep working, but changes to the deployment wait until it is resumed.
oc rollout resume deployment/nginxResume a paused rollout
oc rollout retry dc/frontendRetry a failed deploymentDeletes the deployer and hook pods left by the failed attempt of dc/frontend and runs it again.
oc rollout cancel dc/nginxCancel a running deploymentStops a deployment that has not finished; the documented example targets the deployment config nginx.
oc rollback frontendRoll back a deployment configGoes back to the last deployment that finished successfully.
oc rollback frontend --to-version=3 --dry-runPreview a rollbackShows what returning to version 3 would change without performing it.
oc scale --replicas=3 rs/fooScale to a replica countrs/foo is a replica set; the same form works for deployment/NAME and statefulset/NAME.
oc scale --current-replicas=2 --replicas=3 deployment/mysqlScale only from a known sizeChanges nothing unless mysql currently runs exactly 2 replicas.
oc autoscale deployment foo --min=2 --max=10Autoscale a deploymentKeeps foo between 2 and 10 pods; without a CPU target the default autoscaling policy applies.
oc autoscale rc foo --max=5 --cpu=80%Autoscale on CPU usageAims at 80% CPU utilization with no more than 5 pods.

Routes and services 7

CommandWhat it does
oc expose service nginxExpose routeCreates a route for the service, and the route takes over the service's labels.
oc expose service nginx --hostname=www.example.comRoute with a custom host name
oc expose service nginx --path=/nginxRoute for a URL path
oc expose dc ruby-hello-world --port=8080Expose a deployment config as a serviceCreates a service rather than a route, using the port given with --port.
oc create route edge my-route --service=frontendEdge-terminated route
oc create route passthrough my-route --service=frontendPassthrough route
oc create route reencrypt my-route --service=frontend --dest-ca-cert cert.certRe-encrypt route

Configuration and secrets 15

CommandWhat it does
oc set env dc/myapp STORAGE_DIR=/localSet an environment variableWriting the name with a trailing minus, as in ENV-, removes a variable instead.
oc set env pods --all --listList environment variables
oc set env --from=secret/mysecret dc/myappLoad variables from a secret--from=configmap/NAME works the same way, and --prefix adds a prefix to the names.
oc create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecretCreate a secret from values
oc create secret generic my-secret --from-file=path/to/barCreate a secret from filesEach file in the folder becomes one key of the secret.
oc create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2Create a config map from values
oc create configmap my-config --from-file=path/to/barCreate a config map from files
oc extract secret/testExtract a secret to diskWrites the secret's data into the current directory; --to picks another directory.
oc extract configmap/nginx --to=-Print a config map's data
oc secrets link serviceaccount-name pull-secret --for=pullLink a pull secretThe service account then uses that secret automatically when pulling pod images.
oc set image dc/nginx busybox=busybox nginx=nginx:1.9.1Change container imagesEach CONTAINER=IMAGE pair sets the image of one named container.
oc set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256MiSet CPU and memoryApplies to every container of nginx unless -c picks one.
oc set probe dc/webapp --readiness --get-url=http://:8080/healthzAdd an HTTP readiness probeAn empty host in the URL means the probe goes to the pod IP.
oc set probe dc/myapp --remove --readiness --livenessRemove health probes
oc set volume dc/myapp --add --name=v1 -t pvc --claim-size=1G --overwriteMount a new persistent volumeCreates a 1G persistent volume claim and puts it in place of volume v1.

Editing and deleting resources 13

CommandWhat it does
oc create -f ./pod.jsonCreate from a file
oc apply -f ./pod.jsonApply a configuration file
oc apply -k dir/Apply a kustomizationReads the kustomization.yaml file inside that directory.
oc edit svc/registryEdit a resource on the cluster
oc patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'Patch a resourceApplies a strategic merge patch given inline as JSON.
oc diff -f pod.jsonDiff resources in a file
oc replace --force -f ./pod.jsonForce-replace a resourceDeletes the object and then creates it again from the file.
oc delete -f ./pod.jsonDelete from a file
oc delete pods,services -l name=myLabelDelete by label
oc delete pod foo --forceForce-delete a podMeant for a pod stuck on a node that is down.
oc label pods foo unhealthy=trueAdd a labelAdd --overwrite when the label already exists and its value should change.
oc label pods foo bar-Remove a labelA minus sign after the key removes that label if it is present.
oc annotate pods foo description='my frontend'Add an annotation

Roles and permissions 10

CommandWhat it does
oc policy add-role-to-user view user1Grant a project roleGives user1 the view role in the current project only.
oc policy add-role-to-user edit -z serviceaccount1Grant a role to a service account-z names a service account of the current project instead of a user.
oc adm policy add-cluster-role-to-user system:build-strategy-docker devuserGrant a cluster role to a user
oc adm policy add-cluster-role-to-group cluster-admin cluster-adminsGrant a cluster role to a group
oc adm policy remove-cluster-role-from-user system:build-strategy-docker devuserRevoke a cluster role
oc adm policy add-scc-to-user privileged -z serviceaccount1Grant an SCC to a service account
oc adm policy scc-subject-review -u bob -f myresource.yamlCheck SCC admission for a userReports if bob is allowed to create the pod defined in myresource.yaml.
oc adm groups new my-group user1 user2Create a group with users
oc adm groups add-users my-group user1 user2Add users to a group
oc adm groups remove-users my-group user1 user2Remove users from a group

Cluster administration 19

CommandWhat it does
oc adm must-gatherCollect cluster diagnosticsRuns with the standard plug-in image and saves the results under a new ./must-gather.local folder.
oc adm must-gather --dest-dir=/local/directoryDiagnostics into a chosen folder
oc adm inspect clusteroperator/openshift-apiserverInspect a cluster operatorGathers debugging data for that one operator only.
oc adm top nodeShow node metrics
oc adm top pod --namespace=NAMESPACEPod metrics for a namespace
oc adm node-logs --role master -u kubeletKubelet logs from control plane
oc adm cordon fooMark a node unschedulable
oc adm drain foo --forceDrain a node--force also evicts pods that no replication controller, replica set, job or similar controller manages.
oc adm uncordon fooMark a node schedulable again
oc adm taint nodes foo dedicated=special-user:NoScheduleTaint a node
oc adm certificate approve csr-sqgzpApprove a CSRCSR means certificate signing request; oc adm certificate deny rejects one the same way.
oc adm upgradeShow update statusLists the current update state and the cluster versions you can move to.
oc adm upgrade --to-latest=trueUpdate to the newest version
oc adm release infoShow current release details
oc adm wait-for-stable-clusterWait for stable operatorsReturns once every cluster operator reports stable; --minimum-stable-period sets for how long.
oc adm new-project myproject --node-selector='type=user-node,region=east'Project with a node selector
oc adm prune builds --orphans --confirmPrune old buildsWithout --confirm the command only reports what it would delete.
oc adm prune deployments --keep-complete=1 --confirmPrune old deploymentsKeeps only the latest complete deployment of each deployment config.
oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m --confirmPrune unused imagesSpares images younger than an hour and the three newest revisions of each tag.

Help and shell setup 6

CommandWhat it does
oc helpGeneral CLI helpLists every available command with a short description, including the adm group for administrators.
oc create --helpHelp for one commandPut --help after any command to print its usage line and flags.
oc explain podsExplain a resource typeShows the description and the fields of the resource as the API defines them.
oc explain pods.spec.containersExplain one field
oc completion bash > oc_bash_completionGenerate Bash completionCopy the file to /etc/bash_completion.d/ and Tab completion works in new terminals.
oc plugin listList installed pluginsPlugins are executables on your PATH whose names begin with oc- or kubectl-.

Notes

Logging in and choosing a project

oc login API_SERVER_URL -u USERNAME -p PASSWORD authenticates against the cluster API; the web console's Copy login command produces an equivalent line with a token, and oc login CLUSTER_URL --web does the same through a browser. A project is a Kubernetes namespace tied to authenticated users: oc new-project my-project creates one and switches to it, oc project myapp switches, and oc project shows the one in use. From there oc get pods, oc describe pods/nginx and oc logs cakephp-ex-1-deploy behave like their kubectl counterparts, and oc rsh foo opens a shell in a container without the exec syntax.

Building and deploying

oc new-app https://github.com/sclorg/cakephp-ex builds and deploys straight from a repository, picking a builder image for the language it finds; there is no separate Git flag, you pass the URL itself, or builder~URL as in oc new-app centos/ruby-25-centos7~https://github.com/sclorg/ruby-ex.git. oc new-app --image=myregistry.com/mycompany/mysql --name=private starts from an image instead. oc start-build hello-world triggers a rebuild. oc rollout status deployment/nginx, oc rollout undo deployment/abc and oc rollout restart deployment/nginx are documented with standard Deployments, while oc rollout latest dc/nginx and oc rollback frontend exist for DeploymentConfig objects, the OpenShift-specific type.

Exposing and scaling

oc expose service nginx creates a Route, the OpenShift-specific object that gives a service a host name; --hostname and --path shape it, and oc create route edge my-route --service=frontend and its passthrough and reencrypt siblings create TLS routes. oc scale --replicas=3 rs/foo changes the replica count directly, and oc autoscale deployment foo --min=2 --max=10 hands it to an autoscaler. For anything the table does not cover, oc explain pods describes an object's fields, oc help lists every command, and oc adm holds the administrator commands.

Questions

How do I log in to an OpenShift cluster from the terminal?

Run oc login API_SERVER_URL -u USERNAME -p PASSWORD with the full API URL, for example https://api.my-cluster.example.com:6443. Copy login command in the web console gives a ready-made token line, and oc login CLUSTER_URL --web logs in through a browser.

How do I switch to another OpenShift project?

oc project myapp switches to the project myapp, oc project shows the one in use and oc projects lists the projects you can see.

What does oc add on top of kubectl?

oc has the same capabilities as kubectl and adds support for OpenShift resources such as DeploymentConfig, BuildConfig, Route and ImageStream, a built-in login command, projects, and helpers like oc new-app and oc new-project. A supported kubectl binary ships with OpenShift Container Platform as well.

How do I open a shell inside an OpenShift pod?

oc rsh foo opens a shell in the first container of pod foo. With exec the equivalent is oc exec mypod -c ruby-container -i -t -- bash -il, and oc debug deploy/test starts a separate debug pod for a deployment instead of entering a running one.

Sources and checks

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.