Back to Origin

OpenShift Command-Line Interface

docs/cli.md

4.1.025.0 KB
Original Source

OpenShift Command-Line Interface

The oc command line tool is used to interact with the OpenShift and Kubernetes HTTP API(s). oc is an alias for openshift cli.

oc is verb focused. The base verbs are get, create, delete, replace, and describe. These verbs can be used to manage both Kubernetes and OpenShift resources. Overall, there are six command groups: basic, build and deploy, application modification, troubleshooting and debugging, advanced, and settings.

Some verbs support the -f flag, which accepts regular file path, URL or - for the standard input. For most actions, both JSON and YAML file formats are supported.

Use oc --help for a full list of the verbs and subcommands available. A detailed list of examples for the most common verbs and subcommands is documented in the oc by example and oadm by example documents.

Common Flags

CLI commands support both local (specific to the given command) and global (works for every command available) flags. Some of the most common global flags are:

NameDescription
--namespace (-n) nsUse ns as the namespace scope for the CLI request (default default).
--ns-path filenameLook in filename for the default namespace.
--match-server-versionRequire server version to match client version.
--loglevel nSet the log verbosity level to n (between 0-5, default 0).
--server (-s) hostConnect to host for API service.
--client-certificate filenameLook in filename for the TLS client certificate.
--client-key filenameLook in filename for the TLS client key.
--certificate-authority filenameLook in filename for the CA certificate.
--auth-path filenameLook in filename for the auth info (for HTTPS).
--api-version versionSpecify API version version to use against the server.
--insecure-skip-tls-verifySkip SSL certificate validation (makes HTTPS insecure).
--help (-h)Display help for the specified command.

Use oc options for a full list of all global flags available.

Basic Commands

oc

This displays the list of available commands.

oc login

This retrieves a session token that allows you to act as a user. Invoked without arguments, oc login prompts for a username and a password. For example, these two invocations are identical:

bash
$ oc login
Username: test
Password: test

$ oc login -u test -p test

See also oc logout and oc whoami.

oc new-project

This creates a new project, with the currently logged-in user as the project admin. Option --display-name specifies the user-facing name of the project. Option --description specifies its description.

For example:

bash
$ oc new-project web-team-dev \
  --display-name="Web Team Development" \
  --description="Development project for the web team."

Note that we use double-quotes around the option arguments.

oc new-app

This creates a new application in OpenShift with the specified source code, templates, and images. It builds up the components of an application using images, templates, or code that has a public repository. It looks up images on the local Docker installation (if available), a container image registry, or an OpenShift image stream. If you specify a source code URL, it sets up a build that takes the source code and converts it into an image that can run in a pod. Local source must be in a git repository that has a remote repository that the OpenShift instance can see. The images will be deployed via a deployment configuration, and a service will be connected to the first public port of the app. You may either specify components using the various existing flags or let new-app autodetect what kind of components you have provided.

If you provide source code, you may need to run a build with oc start-build after the application is created.

The general form is:

bash
$ oc new-app <component> [options]

where component is the same as for oc new-build. The options are:

OptionDescription
--code dirUse source code in dir
--context-dir dirUse dir as context dir in the build
--docker-image imageInclude container image image in the app
--env (-e) k=vSet env var k to value v
--file filenameUse template in filename
--group comp1+comp2Group together components comp1 and comp2
--image-stream (-i) isUse imagestream is in the app
--insecure-registryBypass cert checks for referenced container images
--labels (-l) k1=v1,...Label all resources with k1=v1,...
--name nameGive name to all generated app artifacts
--no-headersFor default output, don't print headers
--output-template sTemplate string (-o template) or path (-o templatefile)
--output-version versionOutput with version (default api-version)
--output (-o) formatformat is one of: json, yaml, template, templatefile
--param (-p) k=vSet/override parameter k with value v
--strategy sUse build strategy s, one of: docker, source
--template tUse OpenShift stored template t in the app

The template format is golang templates. The following example uses a MySQL image in a private registry to create an app and override application artifacts' names.

bash
$ oc new-app \
  --docker-image=myregistry.com/mycompany/mysql \
  --name=private

See also oc start-build.

oc status

This shows a high level overview of the current project.

See also oc describe and oc get.

oc project

This displays the current project, or switches to another one.

For example:

bash
# Switch to the myapp project
$ oc project myapp

# Display the project currently in use
$ oc project

Build and Deploy Commands

oc start-build

This manually starts a build, using either the specified buildConfig or a build name with the --from-build option.

Other options:

NameDescription
--env, (-e) FOO=barExplicitly set or override environment variable for the current build. Does not change the BuildConfig.
--build-loglevelSet or override the build log level output [0-10] during the build.
--commitSpecify the source code commit identifier the build should use; requires a build based on a Git repository.
--followStart a build and watch its logs until it completes or fails.
--waitWait for a build to complete and exit with a non-zero return code if the build fails.
--from-buildSpecify the name of a build which should be re-run.
--from-dirA directory to archive and use as the binary input for a build.
--from-fileA file use as the binary input for the build; example a pom.xml or Dockerfile. Will be the only file in the build source.
--from-repoThe path to a local source code repository to use as the binary input for a build.
--from-webhookSpecify a webhook URL for an existing build config to trigger.
--git-post-receiveThe contents of the post-receive hook to trigger a build.
--git-repositoryThe path to the git repository for post-receive; defaults to the current directory.
--list-webhooksList the webhooks for the specified build config or build; accepts 'all', 'generic', or 'github'.

Stream the logs of the build if the --follow flag is specified.

bash
$ oc start-build ruby-sample-build
$ oc start-build --from-build=ruby-sample-build-1
$ oc start-build --from-build=ruby-sample-build-1 --follow

See also oc new-build and oc new-app.

oc build-logs

This retrieves the logs from a Build container. It allows you to debug broken Build. If the build is still running, this streams the logs from the container to console. Use oc get builds to obtain a list of builds.

bash
$ oc build-logs rubyapp-build

oc rollback

This reverts the pod and container configuration back to a previous deployment. Scaling and trigger settings are normally left as-is. The general form is:

bash
$ oc rollback <deployment> [options]

The options are:

OptionDescription
--dry-runDisplay what the rollback would do but do not perform the rollback.
--change-triggersInclude the previous deployment's triggers in the rollback.
--change-strategyInclude the previous deployment's strategies in the rollback.
--change-scaling-settingsInclude the previous deployment's replication controller replica count and selector in the rollback.
--output formatDo not roll back; instead, display updated deployment configuration in the specified format, one of: json, yaml, template, templatefile.
-t template-stringUse template-string (with --output template).
-t filenameWrite to filename (with --output templatefile).

The template-string is in golang template format. Here are two examples:

bash
# Perform a rollback.
$ oc rollback deployment-1

# Perform the rollback "manually" by piping back to "oc replace".
$ oc rollback deployment-1 --output=json | oc replace dc deployment -f -

See also oc replace.

oc new-build

This creates a new build with the specified source code. It creates a build configuration for your application using images and code that has a public repository. It looks up the images on the local Docker installation (if available), a container image registry, or an OpenShift image stream. If you specify a source code URL, it sets up a build that takes the source code and converts it into an image that can run inside a pod. Local source must be in a git repository that has a remote repository that the OpenShift instance can see.

Once the build configuration is created you may need to run a build with oc start-build.

The general form is:

bash
$ oc new-build <component> [options]

where component has one of the forms:

FormDescription
imageUse image directly.
imagestreamUse the latest image in imagestream.
pathUse source code found at path.
urlUse source code found at url.
image~urlNote the tilde ~ between image and url. In this case the component is actually made of two sub-components, the image and the source code found at url. Use the image as the base and arrange to build the source code on it.

The options are:

OptionDescription
--code
--image (-i) repositoryFind the specified image in repository.
--labels (-l) k1=v1,k2=v2,...Add labels k1=v1,k2=v2,... to all created objects.
--strategy sUse strategy s (one of: docker, source).
--to-dockerForce the build output to be DockerImage.
--name nameGive generated build artifacts the name name.

The following example creates a NodeJS buildConfig based on the provided image / source code combination:

bash
$ oc new-build openshift/nodejs-010-centos7~https://bitbucket.com/user/nodejs-app

See also oc start-build and oc new-app.

oc cancel-build

This cancels a pending or running build. The general form is:

bash
$ oc cancel-build <build> [options]

The options are:

OptionDescription
--dump-logsDisplay the build logs for the cancelled build.
--restartCreate a new build after the current build is cancelled.

The following example cancels the build named 1da32cvq and restarts it.

bash
$ oc cancel-build 1da32cvq --restart

See also oc new-build.

oc import-image

This imports tag and image information from an external container image registry. For example, the following command imports from the mystream registry.

bash
$ oc import-image mystream

oc scale

This sets a new size for a Replication Controller either directly or via its Deployment Configuration.

bash
# n is the highest deployment number for the dc ruby-hello-world
$ oc scale rc ruby-hello-world-n  --replicas=3
$ oc scale dc ruby-hello-world --current-replicas=3 --replicas=5

oc tag

This tags existing images into one or more image streams. The option --source is a hint for the source type; its value is one of: imagestreamtag, istag, imagestreamimage, isimage, and docker. The general form is:

bash
$ oc tag [--source=<sourcetype>] <source> <dest> [<dest> ...]

For example:

bash
$ oc tag --source=docker openshift/origin-control-plane:latest myproject/ruby:tip

Application Modification Commands

oc get

This displays one or many resources. Possible resources are all OpenShift resources (builds, buildConfigs, deployments, deploymentConfigs, images, imageRepositories, routes, projects, and others) and all Kubernetes resources (pods, replicationControllers, services, minions, events).

bash
$ oc get pods
$ oc get replicationController 1234-56-7890-234234-456456
$ oc get service database
$ oc get -f json pods

Output formatting

You can control the output format by using the -o format flag. By default, oc uses human-friendly printer format for console. You can also control what API version will be used to print the resource by using the --output-version flag. By default, it uses the latest API version.

Available formats include:

ValueDescription
jsonPretty formated JSON format
yamlYAML format
templateUser defined Go template (combined with the -t flag)
templatefileSame as above, but use the template file instead of -t

An example of using -o template to retrieve the name of the first build:

bash
$ oc get builds -o template --template="{{with index .items 0}}{{.metadata.name}}{{end}}"

Selectors

oc get provides also selectors that you can use to filter the output by applying key-value pairs that will be matched with the resource labels:

bash
$ oc get pods -s template=production

This command will return only pods whose labels include "template": "production".

See also oc describe.

oc describe

This functions similar to oc get, but also includes other information related to the specified resource.

bash
$ oc describe service frontend

oc edit

This starts an editor opened to the YAML representation of the specified object. When the editor exits, the object is updated. You can specify the editor through environment variables OC_EDITOR, GIT_EDITOR, or EDITOR. If none of those are set, oc edit uses the vi program. The general form is:

bash
$ oc edit <resource-type>/<name> [options]

The options are:

OptionDescription
--output (-o) formatEdit object as format, one of: json, yaml.
--output-version versionUse API version version.

For example, to edit the service docker-registry in JSON using the v1 API format:

bash
$ oc edit svc/docker-registry --output-version=v1 -o json

oc set env

This updates the environment on a resource with a pod template. The general form is:

bash
$ oc set env <resource-type>/<name> <k1>=<v1> <k2>=<v2>

For example:

bash
$ oc set env dc/app DB_USER=user DB_PASS=pass

oc set volume

This controls the storage associated with various resources. The general form is:

bash
$ oc set volume <resource-type>/<name> --<action> <options>

where action is one of add, remove, list and options depends on action. For example, to arrange for the deployment configuration registry to access the host /opt directory, use:

bash
$ oc set volume dc/registry --add --mount-path=/opt

oc label

This adds labels to a provided resource. It can also overwrite the existing labels by using the --overwrite flag.

bash
$ oc label service frontend foo=bar

oc expose

This exposes containers internally as services or externally via routes. There is also the ability to expose a deployment config, replication controller, service, or pod as a new service on a specified port. If no labels are specified, the new object will re-use the labels from the object it exposes.

bash
# Expose a service as a route
$ oc expose service frontend
# Expose a deployment config as a service and use the specified port and name
$ oc expose dc ruby-hello-world --port=8080 --name=myservice --generator=service/v1

oc delete

This deletes a specified resource.

bash
$ oc delete -f pod.json
$ oc delete pod 1234-56-7890-234234-456456

Troubleshooting and Debugging Commands

oc logs

This dumps the logs from a given Pod container. Use oc get pod <pod-id> to list the containers from a Pod.

bash
$ oc logs frontend-pod -c mysql-container

oc exec

This executes a command in a container. The general form is one of:

bash
$ oc exec -p <pod> [-c <container>] <command>
$ oc exec -p <pod> [-c <container>] [-i] [-t] -- <command> [args...]

If -c <container> is omitted, OpenShift chooses the first container in the pod. The -i (or --stdin) flag passes local stdin to the container. The -t (or --tty) flag arranges for stdin to be a TTY.

Some examples are:

bash
# Get output from running 'date' in 'ruby-container' from pod 123456-7890.
$ oc exec -p 123456-7890 -c ruby-container date

# Switch to raw terminal mode, attach stdin to 'bash' in 'ruby-container'
# from pod 123456-780, and stdout/stderr from 'bash' back to the client.
$ oc exec -p 123456-7890 -c ruby-container -i -t -- bash -il

oc port-forward

This forwards one or more local ports to a pod. The general form is:

bash
$ oc port-forward pod/<pod> <forwarding-spec> [...]

where forwarding-spec is either a single port (integer), or a pair of ports separated by a colon <outside>:<inside>. If outside is omitted or zero, OpenShift chooses a random port as the effective listening port.

Some examples are:

bash
# Listen on ports 5000 and 6000 locally, forwarding data
# to/from ports 5000 and 6000 in the pod.
$ oc port-forward pod/mypod 5000 6000

# Listen on 8888 locally, forwarding to 5000 in the pod.
$ oc port-forward pod/mypod 8888:5000

# Listen on a random port locally, forwarding to 5000 in the pod.
# (These invocations are equivalent.)
$ oc port-forward pod/mypod :5000
$ oc port-forward pod/mypod 0:5000

oc proxy

This runs a proxy to the Kubernetes API server. By default, the proxy listens on port 8001. API endpoints are served under directory /api/ and any static files are served under directory /static/. The general form is:

bash
$ oc proxy [options]

The options are:

OptionDescription
--port (-p) nListen on port n.
--api-prefix dirServe the proxied API under dir.
--www (-w)Enable serving static files.
--www-prefix (-P) dirServe static files under dir.
--disable-filterDisable request filtering.
--accept-hosts rxAccept requests from hosts matching regular expression rx.
--accept-paths rxAccept paths matching regular expression rx.
--reject-paths rxReject paths matching regular expression rx.

WARNING: The --disable-filter flag is dangerous and can leave you vulnerable to XSRF attacks. Use with caution.

The following example runs a proxy on port 8011 with API prefix k8s-api.

bash
$ oc proxy -p 8011 --api-prefix k8s-api

This makes, for instance, the pods API (version 1) available at localhost:8011/k8s-api/v1/pods/.

Advanced Commands

oc create

This creates resources. It does not require pointers about what resource it should create because it reads it from the provided JSON/YAML. After successful creation, the resource name will be printed to the console.

bash
$ oc create -f pod.json
$ cat pod.json | oc create -f -
$ oc create -f http://server/pod.json

oc replace

This replaces existing resources.

bash
$ oc replace -f pod.json
$ cat pod.json | oc replace -f -
$ oc replace -f http://server/pod.json

oc patch

This updates one or more fields of a resource using strategic merge patch. The general form is:

bash
$ oc patch <resource-type> <name> -p <patch>

where patch is a JSON or YAML map expression that names one or more fields and their new values. The following example sets the spec.unschedulable field of the app node to the value true:

bash
$ oc patch node app -p '{"spec":{"unschedulable":true}}'

The equivalent operation with YAML is:

bash
$ oc patch node app -p '
spec:
  unschedulable: true
'

In both cases, the top-level field is spec and its value is another map expression whose sole key is unschedulable.

oc process

This processes a Template into a valid Config resource. The processing will take care of generating values for parameters specified in the Template and substituting the values in the corresponding places. An example Template can be found in examples/sample-app/application-template-stibuild.json.

bash
$ oc process -f examples/sample-app/application-template-stibuild.json > config.json
$ oc process -f template.json | oc create -f -

Settings Commands

oc logout

This destroys the session token, preventing further access until next login (with oc login).

oc config

This manages the OpenShift kubeconfig files. The general form is:

bash
$ oc config <subcommand> [<arg> ...]

The subcommands are:

SubcommandDescription
setSet an individual value in a kubeconfig file.
set-clusterSet a cluster entry in kubeconfig.
set-contextSet a context entry in kubeconfig.
set-credentialsSets a user entry in kubeconfig.
unsetUnset an individual value in a kubeconfig file.
use-contextSet the current-context in a kubeconfig file.
viewDisplay merged kubeconfig settings or a specified kubeconfig file.

The following example changes the config context to use:

bash
$ oc config use-context my-context

oc whoami

This displays information about the current session. If invoked without arguments, oc whoami displays the currently authenticated username. Flag -t (or --show-token) means to instead display the session token. Flag -c (or --show-context) means to instead display the user context name.

bash
$ oc whoami -t
<token>

See also oc login.