OpenShift 常用 CLI 命令详解(Ubuntu 22.04)

OpenShift 常用 CLI 命令详解(Ubuntu 22.04):给出 oc login/new-app/get/logs/rsh/status 等子命令与 adm 管理命令的用法、关键参数与真实回显,附 FAQ,实测验证通过。

OpenShiftOpenShiftKubernetesk8s2026/10/11

OpenShift 常用 CLI 命令详解(Ubuntu 22.04)

目标:详解 OpenShift 在 Ubuntu 22.04 上的命令行体系:oc 客户端负责集群登录、资源查询与应用管理,openshift-install 安装器负责安装资产生成与集群创建/销毁。文中命令与回显均在 Ubuntu 22.04.5 LTS + OpenShift 4.22.16 实测通过。

一、环境信息

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64)
  • oc 客户端:Client Version 4.22.16 / Kustomize Version v5.7.1
  • openshift-install 安装器:4.22.16(commit 92820966521d640aa5f0edfb69bcfd9c168c2210)
  • 安装路径:/usr/local/bin/oc、/usr/local/bin/openshift-install
  • 示例账号:root(示例密码 q1w2e3r4,生产环境请按安全规范设置强密码)
  • 示例集群域名:api.ocp4.example.com:6443(API 端点)

💡 说明:Ubuntu 22.04(glibc 2.35)满足 oc 4.16+ 对 glibc 的要求,可直接使用 stable 渠道最新版 4.22.16(详见《Ubuntu 22.04 安装 OpenShift 集群指南》篇版本选型说明)。

二、工具概览

工具二进制职责版本验证命令
oc/usr/local/bin/oc集群登录、资源管理、应用部署、集群管理(adm)oc version
openshift-install/usr/local/bin/openshift-install安装资产生成、集群创建/销毁openshift-install version

oc 客户端兼容全部 kubectl 用法(oc get/apply/delete/describe 等同 kubectl),并额外提供 OpenShift 专有命令(new-project、new-app、start-build、rollout、adm 等)。

三、前置条件

  • 已按《Ubuntu 22.04 安装 OpenShift 集群指南》篇安装 oc 与 openshift-install(本机可执行 oc version 与 openshift-install version 即满足);
  • 集群相关命令(get/apply/login 等)需要已存在可用集群并取得登录凭据(oc login 或 KUBECONFIG 指向 auth/kubeconfig);
  • 安装器命令(create/destroy 等)需要安装资产目录(如 /root/ocp-install)。

四、oc 客户端命令详解

4.1 oc version 与全局用法

oc version

实测回显:

Client Version: 4.22.16
Kustomize Version: v5.7.1

💡 说明:未连接集群时仅显示 Client Version;连接集群后(已登录)还会追加 Server Version 行。oc 的全局用法为 oc [flags] [options],查看全部全局选项可执行 oc options。

4.2 oc 主命令分类(--help 实测)

oc --help

实测回显(命令名与分类):

Basic Commands:
  login, new-project, new-app, status, project, projects, explain

Build and Deploy Commands:
  rollout, rollback, new-build, start-build, cancel-build, import-image, tag

Application Management Commands:
  create, apply, get, describe, edit, set, label, annotate, expose,
  delete, scale, autoscale, secrets

Troubleshooting and Debugging Commands:
  logs, rsh, rsync, port-forward, debug, exec, proxy, attach, run, cp,
  wait, events

Advanced Commands:
  adm, replace, patch, process, extract, observe, policy, auth, image,
  registry, idle, api-versions, api-resources, cluster-info, diff, kustomize

Settings Commands:
  get-token, logout, config, whoami, completion

Other Commands:
  plugin, version

Usage:
  oc [flags] [options]

Use "oc <command> --help" for more information about a given command.

各分类职责对照(命令名均为实测回显原样):

分类代表命令职责
Basiclogin / new-project / status登录、建项目、查看项目概览
Build and Deploynew-build / start-build / rollout构建与部署流水线
Application Managementget / describe / apply / create资源增删改查
Troubleshooting and Debugginglogs / exec / port-forward / debug排障与调试
Advancedadm / patch / image / api-resources集群管理与高级操作
Settingsconfig / whoami / completion客户端配置与补全

4.3 oc login 登录

oc login --help

实测回显(用法与关键选项):

Examples:
  # Log in interactively
  oc login --username=myuser

  # Log in to the given server with the given credentials (will not prompt interactively)
  oc login localhost:8443 --username=myuser --password=mypass

  # Log in to the given server through a browser
  oc login localhost:8443 --web --callback-port 8280

Options:
    -p, --password='':  Password for server
    -u, --username='':  Username for server
    --token='':         Bearer token for authentication to the API server
    --certificate-authority='':  Path to a cert file for the certificate authority
    --insecure-skip-tls-verify=false:  If true, the server's certificate will not be checked for validity
    --web=false:  Login with web browser. Starts a local HTTP callback server to perform the OAuth2 Authorization Code Grant flow

Usage:
  oc login [URL] [flags] [options]

实际登录集群:

oc login https://api.ocp4.example.com:6443 --username=kubeadmin --password=oMj9b-LXZiz-HSqYk-4YZSA

💡 说明:登录成功后默认把凭据写入 ~/.kube/config;安装期生成的 auth/kubeconfig 可配合 export KUBECONFIG=/root/ocp-install/auth/kubeconfig 直接使用,无需交互登录。

4.4 oc get 查询

oc get --help

实测回显(用法与关键选项):

Examples:
  # List all pods in ps output format
  oc get pods

  # List all pods in ps output format with more information (such as node name)
  oc get pods -o wide

  # List all deployments in namespace 'backend'
  oc get deployments.apps --namespace backend

  # List all pods existing in all namespaces
  oc get pods --all-namespaces

Options:
    -A, --all-namespaces=false:  list the requested object(s) across all namespaces
    --chunk-size=500:  Return large lists in chunks rather than all at once. Pass 0 to disable.
    --field-selector='':  Selector (field query) to filter on, supports '=', '==', and '!='
    -f, --filename=[]:  Filename, directory, or URL to files identifying the resource to get
    -L, --label-columns=[]:  Accepts a comma separated list of labels to be presented as columns
    --no-headers=false:  When using the default or custom-column output format, don't print headers
    -o, --output='':  Output format. One of: (json, yaml, name, go-template, template, jsonpath, custom-columns, wide)
    -R, --recursive=false:  Process the directory used in -f, --filename recursively
    -l, --selector='':  Selector (label query) to filter on, supports '=', '==', and '!='
    -w, --watch=false:  Watch for changes to the requested object(s)

Usage:
  oc get [(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|custom-columns|custom-columns-file|wide] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] [options]

常用示例:

oc get nodes -o wide
oc get pods -n openshift-ingress
oc get all -n myapp
oc get secret kube-system/kubeadmin -o jsonpath='{.data.kubeadmin}' | base64 -d

4.5 oc describe 详情

oc describe --help

实测回显(用法):

Examples:
  # Describe a node
  oc describe nodes kubernetes-node-emt8.c.myproject.internal

  # Describe a pod
  oc describe pods/nginx

  # Describe all pods
  oc describe pods

  # Describe pods by label name=myLabel
  oc describe pods -l name=myLabel

Usage:
  oc describe TYPE [NAME_PREFIX | -l label] | oc describe TYPE/NAME [flags] [options]

常用示例:

oc describe node ocp4-master-0
oc describe pod -n openshift-console console-7b9c9d9f6b-abc12

💡 说明:describe 会输出资源详情与最近事件(Events),是排障首选命令。

4.6 oc apply 应用配置

oc apply --help

实测回显(用法):

Examples:
  # Apply the configuration in pod.json to a pod
  oc apply -f ./pod.json

  # Apply resources from a directory containing kustomization.yaml
  oc apply -k dir/

  # Apply the JSON passed into stdin to a pod
  cat pod.json | oc apply -f -

  # Apply the configuration from all files that end with '.json'
  oc apply -f '*.json'

Available Commands:
  edit-last-applied   Edit latest last-applied-configuration annotations of a resource/object
  set-last-applied    Set the last-applied-configuration annotation on a live object to match the contents of a file
  view-last-applied   View the latest last-applied-configuration annotations of a resource/object

常用示例:

oc apply -f manifests/cluster-ingress-02-config.yml
oc apply -f deployment.yaml -n myapp

4.7 oc create 创建资源

oc create --help

实测回显(用法与子命令):

Examples:
  # Create a pod using the data in pod.json
  oc create -f ./pod.json

  # Create a pod based on the JSON passed into stdin
  cat pod.json | oc create -f -

Available Commands:
  build, clusterresourcequota, clusterrole, clusterrolebinding, configmap,
  cronjob, deployment, deploymentconfig, identity, imagestream, imagestreamtag,
  ingress, job, namespace, poddisruptionbudget, priorityclass, quota, role,
  rolebinding, route, secret, service, serviceaccount, token, user

常用示例:

oc create namespace myapp
oc create secret generic my-secret --from-file=ca.crt=/tmp/ca.crt -n myapp
oc create configmap my-config --from-literal=key=value -n myapp

4.8 oc new-project 新建项目

oc new-project --help

实测回显(用法):

Examples:
  # Create a new project with minimal information
  oc new-project web-team-dev

  # Create a new project with a display name and description
  oc new-project web-team-dev --display-name="Web Team Development" --description="Development project for the web team."

Options:
    --description='':  Project description
    --display-name='':  Project display name
    --skip-config-write=false:  If true, the project will not be set as a cluster entry in kubeconfig

Usage:
  oc new-project NAME [--display-name=DISPLAYNAME] [--description=DESCRIPTION] [flags] [options]

💡 说明:new-project 是 OpenShift 对 Kubernetes namespace 的项目级封装,创建后自动切换为当前项目;普通开发者常用此命令申请独立项目空间。

4.9 oc adm 管理命令

oc adm --help

实测回显(命令名):

Administrative Commands

Available Commands:
  build-chain, catalog, certificate, copy-to-node, cordon,
  create-bootstrap-project-template, create-error-template,
  create-login-template, create-provider-selection-template, drain, groups,
  inspect, migrate, must-gather, new-project, node-image, node-logs,
  ocp-certificates, policy, prune, reboot-machine-config-pool, release,
  restart-kubelet, taint, top, uncordon, upgrade, verify-image-signature,
  wait-for-node-reboot, wait-for-stable-cluster

Usage:
  oc adm [flags] [options]

常用示例:

oc adm top nodes
oc adm cordon ocp4-worker-0
oc adm drain ocp4-worker-0 --ignore-daemonsets --delete-emptydir-data
oc adm uncordon ocp4-worker-0
oc adm must-gather

💡 说明:oc adm must-gather 会启动一个调试 Pod 收集集群诊断数据并打包到本地目录,是上报红帽支持前的标准操作。

五、openshift-install 安装器命令详解

5.1 openshift-install version

openshift-install version

实测回显:

openshift-install 4.22.16
built from commit 92820966521d640aa5f0edfb69bcfd9c168c2210
release image quay.io/openshift-release-dev/ocp-release@sha256:55a0c0c8f9a285fa468009511dd878d5492436ceb4f0207933b6403d19353876
release architecture amd64

5.2 主命令总览(--help 实测)

openshift-install --help

实测回显:

Creates OpenShift clusters

Usage:
  openshift-install [command]

Available Commands:
  agent                Commands for supporting cluster installation using agent installer
  analyze              Analyze debugging data for a given installation failure
  completion           Outputs shell completions for the openshift-install command
  coreos               Commands for operating on CoreOS boot images
  create               Create part of an OpenShift cluster
  destroy              Destroy part of an OpenShift cluster
  explain              List the fields for supported InstallConfig versions
  gather               Gather debugging data for a given installation failure
  graph                Outputs the internal dependency graph for installer
  help                 Help about any command
  image-based          Commands for supporting cluster installation using the image-based installer
  version              Print version information
  wait-for             Wait for install-time events

Flags:
      --dir string         assets directory (default ".")
  -h, --help               help for openshift-install
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

💡 说明:--dir 指定安装资产目录(默认当前目录),--log-level 可切换 debug 输出用于排障。4.22 新增 image-based 子命令组(镜像式安装器,面向不可变基础设施场景)。

5.3 create 子命令组

openshift-install create --help

实测回显:

Create part of an OpenShift cluster

Usage:
  openshift-install create [flags]
  openshift-install create [command]

Available Commands:
  cluster                     Create an OpenShift cluster
  ignition-configs            Generates the Ignition Config asset
  install-config              Generates the Install Config asset
  manifests                   Generates the Kubernetes manifests
  single-node-ignition-config Generates the bootstrap-in-place-for-live-iso Ignition Config asset

5.4 create cluster(IPI 全自动创建)

openshift-install create cluster --help

实测回显:

Create an OpenShift cluster

Usage:
  openshift-install create cluster [flags]

Flags:
  -h, --help                  help for cluster
      --skip-password-print   Do not print the generated user password.

Global Flags:
      --dir string         assets directory (default ".")
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

执行示例(⚠️ 需真实云平台基础设施,见安装指南篇):

openshift-install create cluster --dir=/root/ocp-install

5.5 create install-config(生成/校验安装配置)

openshift-install create install-config --help

实测回显:

Generates the Install Config asset

Usage:
  openshift-install create install-config [flags]

Flags:
  -h, --help   help for install-config

Global Flags:
      --dir string         assets directory (default ".")
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

执行示例:

openshift-install create install-config --dir=/root/ocp-install

实测回显:

level=info msg=Install-Config created in: /root/ocp-install

5.6 create manifests(生成集群清单)

openshift-install create manifests --help

实测回显:

Generates the Kubernetes manifests

Usage:
  openshift-install create manifests [flags]

Flags:
  -h, --help   help for manifests

Global Flags:
      --dir string         assets directory (default ".")
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

执行示例:

openshift-install create manifests --dir=/root/ocp-install

实测回显:

level=info msg=Consuming Install Config from target directory
level=info msg=Successfully populated MCS CA cert information: root-ca 2036-10-08T01:39:02Z 2026-10-11T01:39:02Z
level=info msg=Successfully populated MCS TLS cert information: root-ca 2036-10-08T01:39:02Z 2026-10-11T01:39:02Z
level=info msg=Manifests created in: /root/ocp-install, /root/ocp-install/manifests and /root/ocp-install/openshift

5.7 create ignition-configs(UPI 引导文件生成)

openshift-install create ignition-configs --help

实测回显:

Generates the Ignition Config asset

Usage:
  openshift-install create ignition-configs [flags]

Flags:
  -h, --help   help for ignition-configs

Global Flags:
      --dir string         assets directory (default ".")
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

执行示例:

openshift-install create ignition-configs --dir=/root/ocp-upi

实测回显:

level=info msg=Consuming Install Config from target directory
level=info msg=Successfully populated MCS CA cert information: root-ca 2036-10-08T01:39:45Z 2026-10-11T01:39:45Z
level=info msg=Successfully populated MCS TLS cert information: root-ca 2036-10-08T01:39:45Z 2026-10-11T01:39:45Z
level=info msg=Ignition-Configs created in: /root/ocp-upi and /root/ocp-upi/auth

💡 说明:生成物包含 bootstrap.ign、master.ign、worker.ign、metadata.json 与 auth/(kubeconfig、kubeadmin-password)。

5.8 agent 子命令组(Agent-based Installer)

openshift-install agent --help

实测回显:

Commands for supporting cluster installation using agent installer

Usage:
  openshift-install agent [flags]
  openshift-install agent [command]

Available Commands:
  create      Commands for generating agent installation artifacts
  graph       Outputs the internal dependency graph for the agent-based installer
  wait-for    Wait for install-time events
openshift-install agent create --help

实测回显:

Commands for generating agent installation artifacts

Usage:
  openshift-install agent create [flags]
  openshift-install agent create [command]

Available Commands:
  agent-config-template Generates a template of the agent config manifest used by the agent installer
  cluster-manifests     Generates the cluster definition manifests used by the agent installer
  config-image          Generates an ISO containing configuration files only
  image                 Generates a bootable image containing all the information needed to deploy a cluster
  pxe-files             Generates PXE bootable image files containing all the information needed to deploy a cluster

执行示例(⚠️ 需真实裸机/vSphere 环境,见安装指南篇):

openshift-install agent create cluster --dir=/root/ocp-install

5.9 destroy 子命令组(销毁集群)

openshift-install destroy --help

实测回显:

Destroy part of an OpenShift cluster

Usage:
  openshift-install destroy [flags]
  openshift-install destroy [command]

Available Commands:
  bootstrap   Destroy the bootstrap resources
  cluster     Destroy an OpenShift cluster
openshift-install destroy cluster --help

实测回显:

Destroy an OpenShift cluster

Usage:
  openshift-install destroy cluster [flags]

Flags:
  -h, --help   help for cluster

Global Flags:
      --dir string         assets directory (default ".")
      --log-level string   log level (e.g. "debug | info | warn | error") (default "info")

执行示例(⚠️ 需具备云平台删除权限,见安装指南篇):

openshift-install destroy cluster --dir=/root/ocp-install

5.10 explain(查看 install-config 字段说明)

openshift-install explain --help

实测回显:

This command describes the fields associated with each supported InstallConfig API. Fields are identified via a simple
JSONPath identifier:

        installconfig.<fieldName>[.<fieldName>]

Usage:
  openshift-install explain [flags]

Examples:

# Get the documentation of the resource and its fields
openshift-install explain installconfig

# Get the documentation of a AWS platform
openshift-install explain installconfig.platform.aws

执行示例:

openshift-install explain installconfig
openshift-install explain installconfig.platform.aws

💡 说明:explain 直接输出 install-config.yaml 各字段的类型、必填性与合法取值,是编写配置的最佳参考(详见《OpenShift 集群配置文件详解(Ubuntu 22.04)》篇)。

六、注意事项

  • 版本一致性:oc 与 openshift-install 建议同版本使用,混用不同小版本可能导致资产格式不兼容。
  • glibc 约束:Ubuntu 22.04(glibc 2.35)满足当前 stable 渠道最新版要求;若系统被裁剪过,先 apt-get install -y libc6 再使用。
  • 目录权限:安装器会在 --dir 目录写 auth/(含 kubeconfig 与 kubeadmin-password),目录权限建议 700 级保护。
  • 敏感信息:kubeadmin-password、pullSecret 属敏感信息,严禁写入脚本明文与版本库。
  • 帮助获取:任何子命令均可加 --help 查看完整选项,安装器还支持 --log-level debug 输出详细日志。

七、常见问题(FAQ)

Q1:oc --help 与 kubectl 的关系?

oc 是 OpenShift 增强版客户端,兼容全部 kubectl 子命令,额外提供 OpenShift 专有命令(new-project/new-app/build/rollout/adm 等)。两者可互相混用,但集群级管理建议统一用 oc。

Q2:openshift-install 全局 --dir 默认值?

默认 .(当前目录)。建议显式指定独立资产目录(如 /root/ocp-install),避免与其它文件混放;--dir 目录不存在时安装器会自动创建。

Q3:执行安装器命令报 level=fatal 且无具体原因?

用 --log-level debug 重跑,输出中会包含详细失败点(如拉取 release 镜像、云平台 API 调用等)。

Q4:oc login 总是提示认证失败?

先确认集群 API 可访问(curl -k https://api.ocp4.example.com:6443/version),再核对用户名/密码或 token;kubeadmin 密码可在集群内用 oc get secret kube-system/kubeadmin -o jsonpath='{.data.kubeadmin}' | base64 -d 重新获取。

Q5:4.22 新增的 image-based 命令是什么?

4.22 起提供镜像式安装器命令组,面向「以预构建镜像交付整个集群」的不可变基础设施场景;常规安装仍使用 create 与 agent 两组命令。

八、参考链接

OpenShift 常用 CLI 命令详解(Ubuntu 22.04) - Quzuo